How do I write a MATLAB code for A (in body) that doubles the elements that are greater than 6, and raises to the power of 2 the elements that are negative but greater than -2?
Afficher commentaires plus anciens
A=[5 10 -3 8 0; -1 12 15 20 -6]
Réponses (2)
sixwwwwww
le 10 Oct 2013
Here is code for your problem
A=[5 10 -3 8 0; -1 12 15 20 -6];
dim = size(A);
B = nan(dim(1), dim(2));
for i = 1:dim(1)
for j = 1:dim(2)
if A(i,j) >= 6
B(i,j) = 2 * A(i,j);
else if (A(i,j) < 6 && A(i,j) > -2)
B(i,j) = A(i,j) ^ 2;
end
end
end
end
Good luck
4 commentaires
Sam
le 10 Oct 2013
sixwwwwww
le 10 Oct 2013
A=[5 10 -3 8 0; -1 12 15 20 -6];
dim = size(A);
B = nan(dim(1), dim(2));
for i = 1:dim(1)
for j = 1:dim(2)
if A(i,j) >= 6
B(i,j) = 2 * A(i,j);
else if (A(i,j) < 6 && A(i,j) > -2)
B(i,j) = A(i,j) ^ 2;
else
B(i,j) = A(i,j);
end
end
end
end
Here is the code which maintain values which are not used in *2 or ^2 operations. Good luck
Sam
le 10 Oct 2013
Image Analyst
le 10 Oct 2013
Modifié(e) : Image Analyst
le 10 Oct 2013
But it's still doesn't do what you asked. Specifically
A(i,j) < 6 && A(i,j) > -2
does not select "elements that are negative but greater than -2" as you asked for. Use Kelly's answer instead which does it correctly. Plus that solution uses a vectorized approach which is faster and the more MATLAB-ish way to do it.
Kelly Kearney
le 10 Oct 2013
The loops are unnecessary:
A = [5 10 -3 8 0; -1 12 15 20 -6];
A(A > 6) = A(A > 6) .* 2;
A(A < 0 & A > -2) = A(A < 0 & A > -2).^2
A =
5 20 -3 16 0
1 24 30 40 -6
1 commentaire
Sam
le 10 Oct 2013
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!