Ending an If Else loop

7 ビュー (過去 30 日間)
Qwerty1
Qwerty1 2018 年 10 月 30 日
再開済み: Star Strider 2018 年 10 月 30 日
I have a simple script like the one below.
for A=[0:5]
if A==2
B=0;
else B=1;
C=A+B
end
end
I want the script to calculate the value of C for every A, but at the moment the formula for C is within the 'else' part of the loop. Therefore when A=2, no value of C is calculated. I know that I can put the statement within the 'if' part of the loop, but this is a simplified version and I have a much more complex if else loop with a larger statement so want to know if there is a better way.
Thanks.

採用された回答

madhan ravi
madhan ravi 2018 年 10 月 30 日
編集済み: madhan ravi 2018 年 10 月 30 日
A=[0:5]
B=zeros(1,numel(A)) % preallocation for doors and efficiency
C=zeros(1,numel(A))
for I = 1:numel(A)
if A(I)==2
B(I)=0;
else
B(I)=1;
C(I)=A(I)+B(I)
end
end
  1 件のコメント
madhan ravi
madhan ravi 2018 年 10 月 30 日
編集済み: madhan ravi 2018 年 10 月 30 日
Use preallocation for speed and efficiency, use I as an index in order to avoid overwriting

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by