What is wrong with my For loop?
1 回表示 (過去 30 日間)
古いコメントを表示
Hi all
I wrote the code below and it's supposed to be able to multiply the positive values by two and multiply negative values by 3. The code works perfectly for square matrices. For example [-7 10 1 -12;-9 -9 -7 -15;0 -2 8 -2;-15 7 14 -14]. However, it doesn't work for other matrices such as a 3*4. It simply doesn't multiply the last columns by any number. Can anyone please help me?
Thanks
A = input('Enter your matrix: ')
for ii = 1:size(A)
for jj = 1:size(A)
if A(ii,jj) > 0
A(ii,jj) = 2*(A(ii,jj));
else
A(ii,jj) = 3*(A(ii,jj))'
end
end
end
0 件のコメント
採用された回答
KSSV
2017 年 3 月 15 日
編集済み: KSSV
2017 年 3 月 15 日
A = input('Enter your matrix: ')
for ii = 1:size(A,1)
for jj = 1:size(A,2)
if A(ii,jj) > 0
A(ii,jj) = 2*(A(ii,jj));
else
A(ii,jj) = 3*(A(ii,jj)) ;
end
end
end
You are running loop only along the number of times the row's are. Now I have included columns also.
You can achieve the same without loop.
B =A ;
B(A>0) = 2*A(A>0) ;
B(A<0) = 3*A(A<0) ;
0 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!