Logical expression not working with loop and if statement

조회 수: 1 (최근 30일)
Maxence Boels
Maxence Boels 2019년 11월 11일
댓글: Walter Roberson 2019년 11월 11일
I need an array with [1, 1, 0, 1, 0, 0, 1, 1, 0, 1]
N=10;
query_class=9;
n_candidate_class = [9, 9, 4, 9, 5, 5, 9, 9, 5, 9];
imgout = zeros(1,N);
for n = 1:N
for c = 1:N
if query_class == n_candidate_class(n)
imgout(c) = 1;
else
imgout(c) = 0;
end
end
end
  댓글 수: 3
Maxence Boels
Maxence Boels 2019년 11월 11일
Thank you ! Much simpler than I thought.
Do you know what was going wrong in my query?
Walter Roberson
Walter Roberson 2019년 11월 11일
You overwrite each imgout(c ) for each different n value, so you are only getting the result as-if you had run with n=N . You want to be comparing corresponding values, not each one to each other.

댓글을 달려면 로그인하십시오.

채택된 답변

Ankit
Ankit 2019년 11월 11일
편집: Ankit 2019년 11월 11일
Hello Maxence Boels,
this is due to the inner for loop, which is causing problem. for n =1, the inner loop changes its values from 1 to 10, and compares query_class(whose value is 9) to n_candidate_class(1) which is also 9. Hence it return [1,1, 1,1,1,1,1,1,1,1] for the first iteration of n.
N=10;
query_class=9;
n_candidate_class = [9, 9, 4, 9, 5, 5, 9, 9, 5, 9];
imgout = zeros(1,N);
for n = 1:N
if query_class == n_candidate_class(n)
imgout(n) = 1;
else
imgout(n) = 0;
end
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by