Will output a matrix A obtained by modifying an input matrix B in the following way: 1. If an entry in B is greater than or equal to zero then multiply it by 4 2. If an entry in B is less than 0 then add 4 to it.
Show older comments
This is what I have came up with so far.
function [a] = modify_matrix(B)
if B < 0
a = B + 4;
else
a = B * 4;
end
end
The issue I run into is, it just multiplies by 4. If there is anything I need to add or fix to make this equation work? Please help.
Answers (2)
Star Strider
on 2 Dec 2017
This is straightforward with ‘logical indexing’:
B = randi([-1 9], 5, 4) % Create Matrix To Test Code
a = B;
a(a>=0) = a(a>=0)*4;
a(a<0) = a(a<0)+4;
and that could be made even more efficient:
lt0 = a<0;
a = a(lt0)+4 + a(~lt0)*4
If you have to use if...else blocks, you also have to use nested loops, and test each element:
a = zeros(size(B));
for k1 = 1:size(B,1)
for k2 = 1:size(B,2)
if B(k1,k2) >= 0
a(k1,k2) = B(k1,k2)*4;
else
a(k1,k2) = B(k1,k2)+4;
end
end
end
So, it depends on how you want to approach it.
Image Analyst
on 2 Dec 2017
A way similar to the first way Star Strider showed, but slightly different:
function a = modify_matrix(B)
a = B + 4; % Initialize. So far all elements have 4 added.
% Find indexes >= 0
positiveIndexes = B >= 0; % A logical vector.
% Multiply those indexes by 4
a(positiveIndexes) = 4 * B(positiveIndexes);
Categories
Find more on Logical 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!