Simple if statement also executes if condition not met - What am I doing wrong?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Mara Mueller
le 28 Nov 2019
Commenté : Mara Mueller
le 29 Nov 2019
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 commentaires
Réponse acceptée
the cyclist
le 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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!