My loop returns imaginary results!

Hello,
I write this simple code in a loop, and I obtain unwabted imaginary results. Could you please tell me where my mistake is:
SO = 0.5 .* ones(10,1);
A(1,:) = 5.02 * (16.6 / 42) ^ 0.33 * SO(1,:) ^ 0.38;
for i = 2 : 10
A(i,:) = 5.02 * ((16.6 - sum(A(1:i-1,:)))/ 42) ^ 0.33 * SO(i,:) ^ 0.38;
end
Thanks in advance
Maryam S.

 採用された回答

madhan ravi
madhan ravi 2020 年 5 月 30 日
編集済み: madhan ravi 2020 年 5 月 30 日

0 投票

Evaluate the part
((16.6 - sum(A(1:i-1,:)))/ 42)
and see what happens when the sum(...) is greater than 16.6
Note: No loop needed here sum(...) could be replaced by cumsum(...) and linear indexing is sufficient, subscript indexing is not needed here since it’s a vector.

5 件のコメント

Maryam S
Maryam S 2020 年 5 月 30 日
編集済み: madhan ravi 2020 年 5 月 30 日
Thanks Madhan, I see the problem, now I need to replace the NaN values with zero, so I use A(isnan(A)) = 0, but it does not work. Do you think of another solution?
Thanks
Maryam S.
madhan ravi
madhan ravi 2020 年 5 月 30 日
It should work , illustrate for which values it does not work with a simple example.
Maryam S
Maryam S 2020 年 5 月 30 日
from A(7,:) the 16.6 - sum(A(1:i-1,:) gets negative and the resluts get imaginary. But how to replace the imaginary resuts with zero?
madhan ravi
madhan ravi 2020 年 5 月 30 日
After the loop simply use :
real(A)
Maryam S
Maryam S 2020 年 5 月 30 日
real(A) does not give me zeros. I used A(imag(A)~=0) = 0 and my problem was solved, thanks to you Madhan!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

リリース

R2018b

タグ

質問済み:

2020 年 5 月 30 日

コメント済み:

2020 年 5 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by