IF statements with zero

조회 수: 12 (최근 30일)
Lisa Collins
Lisa Collins 2011년 10월 21일
Does matlab have a problem with the number zero? I am learning the basics and trying out an if statement in an m-file called sorttemp to sort ones and zeros in a vector to become either 14 or 19 , but why are all my answers 19...?
EDU>> clear
EDU>> a = [ 0 0 1 1 0 0 ]
a =
0 0 1 1 0 0
EDU>> sorttemp
b =
19 19 19 19 19 19
EDU>>
%sorttemp
n = 1:6;
if a(1,n) <= 0.5;
b(1,n) = 14;
else b(1,n) = 19
  댓글 수: 2
Fangjun Jiang
Fangjun Jiang 2011년 10월 21일
You can use {}Code format next time.
Lisa Collins
Lisa Collins 2011년 10월 23일
Thanks to all who answered, I appreciate it! I now realise the if statement looks at the whole thing not individual elements... I am going to make this more complicated now and develop this so when the sequence goes 0 to 1 the answer is 16. I assumed that b is unknown but accept that it could be set up to have a default value of all 19's.

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

채택된 답변

Wayne King
Wayne King 2011년 10월 21일
Hi Lisa,
a = [ 0 0 1 1 0 0 ];
b = [ 19 19 19 19 19 19];
for n = 1:6
if (a(n) <=0.5)
b(n) = 14;
else
b(n) = 19;
end
end
but more efficient in MATLAB is simply:
b(a<=0.5) = 14;
  댓글 수: 1
Wayne King
Wayne King 2011년 10월 21일
in other words, try
b = [19 19 19 19 19 19];
a = [ 0 0 1 1 0 0 ];
b(a<=0.5) = 14;

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

추가 답변 (1개)

Jan
Jan 2011년 10월 21일
The actual question is: Why are all b set to 19.
n = 1:6;
if a(1,n) <= 0.5
This means explicitely:
if [0, 0, 1, 1, 0, 0] <= 0.5
Now Matlab performs the comparison elementwise:
if [true, true, false, false, true, true]
Finally if needs a single value to decide for a branch, therefore in includes an all automatically:
if all([true, true, false, false, true, true])
No, not all of these values are true, therefore if uses the else branch:
b(1, 1:6) = 19
All b are set to 19.
NOTE: To be exact if inserts: all(condition) && ~isempty(condition).

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by