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?
1 view (last 30 days)
Show older comments
A=[5 10 -3 8 0; -1 12 15 20 -6]
0 Comments
Answers (2)
sixwwwwww
on 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 Comments
Image Analyst
on 10 Oct 2013
Edited: Image Analyst
on 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
on 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
See Also
Categories
Find more on Spectral Measurements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!