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

1 visualización (últimos 30 días)
Atara Bienenstock
Atara Bienenstock el 7 de Mzo. de 2022
Editada: KSSV el 7 de Mzo. de 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

Respuestas (1)

KSSV
KSSV el 7 de Mzo. de 2022
Editada: KSSV el 7 de Mzo. de 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.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by