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?
Ältere Kommentare anzeigen
A=[5 10 -3 8 0; -1 12 15 20 -6]
Antworten (2)
sixwwwwww
am 10 Okt. 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 Kommentare
Sam
am 10 Okt. 2013
sixwwwwww
am 10 Okt. 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
am 10 Okt. 2013
Image Analyst
am 10 Okt. 2013
Bearbeitet: Image Analyst
am 10 Okt. 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
am 10 Okt. 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 Kommentar
Sam
am 10 Okt. 2013
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!