Why does the second matrix start with zeros?

조회 수: 1 (최근 30일)
Spencer Checkoway
Spencer Checkoway 2020년 7월 31일
댓글: Adam Danz 2020년 7월 31일
for i=-10:10
if i<0
a(i+11)=i;
if i>0
b(i+10)=i;
end
end
end
Out of curiosity, why, if I print b, would the matrix start with 10 zeros?
  댓글 수: 1
Adam Danz
Adam Danz 2020년 7월 31일
"Out of curiosity, why, if I print b, would the matrix start with 10 zeros?"
This code should never reach 'b' which would leave 'b' undefined. The i>0 condition is nested within the i<0 condition. So if i<0, than i will never be greater than 0.
Here is your code with correct formatting.
for i=-10:10
if i<0
a(i+11)=i;
if i>0
b(i+10)=i;
end
end
end
My guess is that one of your 'end' lines is misplaced.
Even if you fix it, you'd still have problems getting what you want for reasons described by madhan ravi.

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

채택된 답변

madhan ravi
madhan ravi 2020년 7월 31일
편집: madhan ravi 2020년 7월 31일
MATLAB assigns zero to the previous indices, for better understanding:
clear a
a(11) = 1; % now you will see elements from 1-10 are filled with zeros, if a doesn’t exist already in the workspace
Perhaps what you want is:
ii = -10 : 10;
a = ii(ii < 0)
b = ii(ii >= 0)

추가 답변 (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