What is wrong with my For loop?

4 次查看(过去 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

采纳的回答

KSSV
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 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by