Simple if statement also executes if condition not met - What am I doing wrong?

1 Ansicht (letzte 30 Tage)
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.

Akzeptierte Antwort

the cyclist
the cyclist am 28 Nov. 2019
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.
  2 Kommentare
Mara Mueller
Mara Mueller am 28 Nov. 2019
Hi, Thank you very much for coming back to me so fast.
Indeed when I just create a vector the same way as you did the code works fine. As does your much more elegant one-liner :)
With my original data from work both did not work (As I tried earlier today). I will upload my *.mat file tomorrow morning and hope we can figure it out.
Have a good evening.
Mara Mueller
Mara Mueller am 29 Nov. 2019
Hi cyclist,
While I still dont understand why the for/if is not working. Your ./ solution, also works with the data imported from a *.mat file.
Thanks a lot for that easy solution.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by