assigning answers of logical operators to a vector using a for-loop

1 Ansicht (letzte 30 Tage)
Atara Bienenstock
Atara Bienenstock am 7 Mär. 2022
Bearbeitet: KSSV am 7 Mär. 2022
I was asked to write a function called testLucky.m which will text if inputed values are in the "secretLucky" matrix using a for-loop. The desired output is a logical 1 or 0 representing whether the inputted value is in the matrix or not. Here's what I've got so far:
My problem is that i onlhy want one output - 0 or 1. but I can't figure out how to do it without getting 7 values enery time (for each for statement)
function[y] = testLucky(x)
% testLucky(x) - determines whether input(x) is a lucky number
% return true (1) if x is a lucky number
% return false (0) if x is not a lucky number
secretLucky = [19 22 5 9 11 15 21];
for k=1:7
secretLucky(i)==x
end
end

Antworten (1)

KSSV
KSSV am 7 Mär. 2022
Bearbeitet: KSSV am 7 Mär. 2022
function y = testLucky(x)
% testLucky(x) - determines whether input(x) is a lucky number
% return true (1) if x is a lucky number
% return false (0) if x is not a lucky number
secretLucky = [19 22 5 9 11 15 21];
y = false ;
for k=1:7
if secretLucky(k)==x
y = true ;
break
end
end
end
You can also use ismember. Read about this.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by