HOW TO AVOID OVERWRITING WITH COMBINED FOR/IF LOOPS

1 回表示 (過去 30 日間)
heir ancestors
heir ancestors 2017 年 3 月 3 日
コメント済み: heir ancestors 2017 年 3 月 3 日
Hello everybody ;
I have a problem with combinaison of loops for and if.
Let's say that I have this matrix which is combined of positiv and negativ numbers.
A=[ 1 4 7 -8 -1 -7; -2 1 3 4 5 9; 1 2 5 -8 -7 4;1 2 4 -4 7 -2; -3 5 -7 -1 1 1]
If I want to set a condition to every element depending on its sign, and add 3 for negative numbers while substracting 7 to positive numbers
I wrote then the following code
B=zeros(size(A))
for i=1:length(A)
if A(i)<0
B(i)=A(i)+3
else
B(i)=A(i)-7
end
end
the problem is the overwriting of the matrix B (which I don't understand why) and the non-saving of the results also.
Any help please
thank you

採用された回答

Jan
Jan 2017 年 3 月 3 日
編集済み: Jan 2017 年 3 月 3 日
length(A) is 6, so you process the first 6 elements only. To process the complete matrix:
for i = 1:numel(A)
...
By the way: a vectorized version:
B = A + 3;
B(A >= 0) = A(A >= 0) - 10;
Or:
B = zeros(size(A));
match = (A < 0);
B(match ) = A(match) + 3;
B(~match ) = A(~match ) - 7;
  1 件のコメント
heir ancestors
heir ancestors 2017 年 3 月 3 日
Thank you very much :)

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

その他の回答 (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