Simple if statement also executes if condition not met - What am I doing wrong?
조회 수: 1 (최근 30일)
이전 댓글 표시
I have two vectors, distance and time. I want to calculate speed. But it should only calculate if neither distance nor time are NaN. If one of the two is NaN, the entry in the speed vector shall be NaN. So I wrote the follwing code:
for i = 1:length(dist_psd);
if (isnan(time_psd(i))==0) & (isnan(dist_psd(i))==0)
speed_psd(i) = dist_psd(i)/time_psd(i);
elseif (isnan(time_psd(i))==1) | (isnan(dist_psd(i))==1)
speed_psd(i) = "NaN";
end
end
It is not adding NaN anywhere and still dividing distance by time even if one of the two is NaN.
For example:
and(E(51)==0,F(51)==0)
gives ans = 0
but:
speed_psd(51)
gives ans = 7.112
I tried so many things... I am completely out of ideas why this could be happening.
Working in Matlab R2019a.
댓글 수: 2
채택된 답변
the cyclist
2019년 11월 28일
I ran the following code:
dist_psd = [1 1 1 1 NaN];
time_psd = [1 1 1 NaN NaN];
for i = 1:length(dist_psd);
if (isnan(time_psd(i))==0) & (isnan(dist_psd(i))==0)
speed_psd(i) = dist_psd(i)/time_psd(i);
elseif (isnan(time_psd(i))==1) | (isnan(dist_psd(i))==1)
speed_psd(i) = "NaN";
end
end
I got the result I expect. The last two entries are NaN, as you said you want. (The elseif statement will convert the string to a double to store it.)
You could have just done
speed_psd = dist_psd./time_psd;
instead all of this code.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!