What is wrong with my For loop?

2 views (last 30 days)
Mohammadamin Malek Pour
Mohammadamin Malek Pour on 15 Mar 2017
Edited: KSSV on 15 Mar 2017
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

Accepted Answer

KSSV
KSSV on 15 Mar 2017
Edited: KSSV on 15 Mar 2017
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) ;

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!