Problem with if statement

조회 수: 2 (최근 30일)
Kyle Donk
Kyle Donk 2020년 1월 14일
답변: Steven Lord 2020년 1월 14일
I am trying to create code that says that if any number in an array of 100 numbers (y) is less than two, then count increases by 1. (y is defined earlier in the code)
Can someone tell me what my if statement is saying? I know that's where I am messing up.
PLEASE DO NOT GIVE ME THE COMPLETE ANSWER! I JUST WANT TO KNOW WHAT MY IF STATEMENT CURRENTLY SAYS!
%Display only the number of y-values less than the number 2.0.
count=0;
N=length(y);
for i=1:N
if y<2
count=count+1
end
disp(count)
end

채택된 답변

Steven Lord
Steven Lord 2020년 1월 14일
If you want to check if element i of y is less than 2, that's not what your if statement says. It is checking all the elements of y at each iteration of your for loop. If you look at the documentation for the if keyword it describes how if handles the case where the thing you're testing is not a scalar. That explains why count likely remains at 0 through your entire for loop.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by