Can't apply an IF function with 100000*1 matrix

4 ビュー (過去 30 日間)
Alexandra
Alexandra 2015 年 6 月 4 日
コメント済み: Alexandra 2015 年 6 月 5 日
Hi! I built this code:
if A1 <0
D = 0.8;
elseif A2 <0
D = 0.7;
elseif A3 <0
D = 0.6;
elseif A4 <0
D = 0.5;
else
D = 0.3;
end
My problem is that A1, A2, A3 and A4 are 100000x1 matrixes from Monte Carlo Simulations so I would expect D to be 100000x1 too. Instead I get a flat value like 0.8. What I am doing wrong? The strange part is that it works when test with a 5x1 matrix. Thanks a lot.

採用された回答

James Tursa
James Tursa 2015 年 6 月 4 日
編集済み: James Tursa 2015 年 6 月 4 日
To make your code work, wrap a loop around it. E.g.,
D = zeros(size(A1));
n = numel(D);
for k=1:n
if A1(k) <0
D(k) = 0.8;
elseif A2(k) <0
D(k) = 0.7;
elseif A3(k) <0
D(k) = 0.6;
elseif A4(k) <0
D(k) = 0.5;
else
D(k) = 0.3;
end
end
Or perhaps you might use a vectorized approach. E.g.:
D = 0.3 * ones(size(A1));
D(A4<0) = 0.5;
D(A3<0) = 0.6;
D(A2<0) = 0.7;
D(A1<0) = 0.8;
  1 件のコメント
Alexandra
Alexandra 2015 年 6 月 5 日
Thanks a lot. I wrapped the loop and it did work!

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

その他の回答 (1 件)

Kelly Kearney
Kelly Kearney 2015 年 6 月 4 日
When applied to a vector, if x < 0 is the same as if all(x < 0). It doesn't iterate over the vector, and therefore it returns the single scalar value that you assign.
You need to either loop over all the values, or use logical indexing instead:
D = ones(size(A1)) * 0.3;
D(A1 < 0) = 0.8;
D(A1 >= 0 & A2 < 0) = 0.6;
D(A1 >= 0 & A2 >= 0 & A3 < 0) = 0.4;
D(A1 >= 0 & A2 >= 0 & A3 >= 0 & A4 < 0) = 0.5;

カテゴリ

Find more on Monte-Carlo in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by