How does the cycle for , if work?

11 ビュー (過去 30 日間)
massi
massi 2015 年 3 月 13 日
コメント済み: massi 2015 年 3 月 13 日
Dear All, I have n=[0:1:10] and the column K=[-2,5,-5]. I would like to generate a cycle in which each time It takes an item of n and adds it to K, every time It checks if the sum(K) is zero: if it is zero it must write the value of "n".
I wrote this but it doesn't work:
for n=0:1:10
K=[-2,5,-5];
Z=K+n;
S=sum(Z);
if S==0
n
end
end
Could you help me, please.
Thanks in advance
Best regards
Massimo

回答 (2 件)

Adam
Adam 2015 年 3 月 13 日
K=[-2,5,-5];
n = 0:10'
res = bsxfun( @plus, K, n' );
resSum = sum( res, 2 );
zeroSums = resSum == 0;
n( zeroSums )
should give you the result you want without needing a loop, if I understand your requirements correctly.
  1 件のコメント
massi
massi 2015 年 3 月 13 日
thank you massi

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


James Tursa
James Tursa 2015 年 3 月 13 日
The reason it doesn't produce any output is because the sum is never 0. E.g., print out S each iteration to see what is going on:
for n=0:1:10
K=[-2,5,-5];
Z=K+n;
S=sum(Z);
disp(S);
if S==0
n
end
end
If you think the sum should have been 0 at some point, then you need to re-examine your algorithm and the problem you are solving.
  1 件のコメント
massi
massi 2015 年 3 月 13 日
ok thanks massi

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

カテゴリ

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