필터 지우기
필터 지우기

Problem in if-else if-else structure

조회 수: 4 (최근 30일)
KalMandy
KalMandy 2016년 11월 11일
댓글: KalMandy 2016년 11월 11일
Hi, I have written the following program. But it does not output the result I get from manual calculations. Perhaps I have gone wrong in writing the logic. The program is as below.
if X1(i)==a(i) && X2(i)==b(i)
t(i)= a(i)* b(i);
else if X1(i)== a(i) && X2(i)==NaN && X1(i+1)==a(i+1) && X2(i+1)==NaN
t(i)= a(i)* a(i+1);
else if X1(i)== a(i) && X2(i)==NaN && X1(i+1)==NaN && X2(i+1)==b(i+1)
t(i)= a(i)* b(i+1);
else if X1(i)==NaN && X2(i)== b(i)&& X1(i+1)==a(i+1) && X2(i+1)==NaN
t(i)= b(i)* a(i+1);
else if X1(i)==NaN && X2(i)== b(i)&& X1(i+1)==NaN && X2(i+1)==b(i+1)
t(i)= b(i)* b(i+1);
else
t(i)= 0;
end
end
end
end
end
The input is as below. X1=NaN a(2) NaN a(4) a(5) NaN NaN
X2= NaN b(2) b(3) NaN b(5) NaN NaN
i=1:7 and i=8 equals to i=1
The output is as below.
t= 0 c 0 0 d 0 0
But there should be output at t(3) and t(4). Can anybody point out where I went wrong? Thanks
  댓글 수: 1
KalMandy
KalMandy 2016년 11월 11일
Should I be using a 'switch' in this case? I am new to matlab and have never used 'switch' before. Can someone please help?

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

답변 (1개)

James Tursa
James Tursa 2016년 11월 11일
편집: James Tursa 2016년 11월 11일
You can't compare to NaN with the == operator, since NaN is not equal to anything (including itself). You must use the isnan function. E.g.,
else if X1(i)== a(i) && X2(i)==NaN && X1(i+1)==a(i+1) && X2(i+1)==NaN
should be
else if X1(i)== a(i) && isnan(X2(i)) && X1(i+1)==a(i+1) && isnan(X2(i+1))
etc.
For example,
>> a = nan
a =
NaN
>> a == nan
ans =
0
>> a == a
ans =
0
  댓글 수: 6
KalMandy
KalMandy 2016년 11월 11일
my code is long and I only showed the part where I assume the problem is. I can post it, but I assume that would confuse you. But here it is. I have substituted X1=onpointX1, X2=onpointX2 etc.
KalMandy
KalMandy 2016년 11월 11일
Hi All, I found out where my problem is. I had to create another for loop. Thank you very much!

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by