What is wrong with my For loop?

18 vues (au cours des 30 derniers jours)
Mohammadamin Malek Pour
Mohammadamin Malek Pour le 15 Mar 2017
Modifié(e) : KSSV le 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

Réponse acceptée

KSSV
KSSV le 15 Mar 2017
Modifié(e) : KSSV le 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) ;

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by