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!