フィルターのクリア

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

1 回表示 (過去 30 日間)
Mara Mueller
Mara Mueller 2019 年 11 月 28 日
コメント済み: Mara Mueller 2019 年 11 月 29 日
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
the cyclist 2019 年 11 月 28 日
Can you upload the data in a *.mat file, so that we can run your code?
Mara Mueller
Mara Mueller 2019 年 11 月 29 日
Here are the files...

サインインしてコメントする。

採用された回答

the cyclist
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.
  2 件のコメント
Mara Mueller
Mara Mueller 2019 年 11 月 28 日
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 2019 年 11 月 29 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by