Hi Everyone I have a question about for loops:
I have a cutoff value (that is defined in another for loop, but I think it doesn't matter for my issue). I have individuals C's (Cj) between 0 and 1. Now I want for every element of Cj to check wether it is above or below the cutoff (The resulting EUI is calculated differently), and in the end I want a vector EUI, that gives me the EUI for every element of Cj. After this I want to sum up over all the EUI's.
It doesn't seem to work, can someone spot the mistake?
cutoff(i) = %definition of cutoff
Cj = linspace(0,1)
EUI = zeros(size(Cj));
for j = 1:numel(Cj)
if Cj(j)<cutoff(i)
EUI(j) = %formula;
else
EUI(j) = %formula;
end
end
EUI_total(i) = sum(EUI(j));

 採用された回答

meghannmarie
meghannmarie 2019 年 9 月 11 日
編集済み: meghannmarie 2019 年 9 月 11 日

0 投票

In the last line, you are summing just the last element. Remove the j index.
EUI_total = sum(EUI);
I would vectoize this code if I were you and avoid loop. Try something like this:
cutoff(i) = %definition of cutoff
Cj = linspace(0,1);
EUI = zeros(size(Cj));
idx = Cj < cutoff(i);
EUI(idx) = formula1(Cj(idx));
EUI(~idx) = formula2(Cj(~idx));
EUI_total(i) = sum(EUI);

1 件のコメント

Franziska
Franziska 2019 年 9 月 11 日
you're right, the summing up was the issue. Thank you very much!

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

その他の回答 (1 件)

Matt J
Matt J 2019 年 9 月 11 日
編集済み: Matt J 2019 年 9 月 11 日

0 投票

I don't see any mistakes (that's why posting your error messages and output is always a good thing), however, the whole thing can be done more efficiently with logical indexing in just a few lines
isless=(Cj<cutoff(i));
EUI(isless)= %formula;
EUI(~isless)= %formula;
result=sum(EUI)

カテゴリ

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

質問済み:

2019 年 9 月 11 日

コメント済み:

2019 年 9 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by