Replacing values in matrix that are greater than another matrix

5 views (last 30 days)
I have the following code that, if a value in A is greater than a corresponding value in B, will replace that value with the value in B, returning the result as C.
How could I rewrite this without loops? Thanks in advance.
C=[];
[m n] = size(A);
for i = 1:m
for j = 1:n
if A(i, j) < B(i, j)
C(i, j) = A(i, j);
else
C(i, j) = B(i, j);
end
end
end
disp(C);

Accepted Answer

Adam Danz
Adam Danz on 9 Jan 2020
Edited: Adam Danz on 9 Jan 2020
% Create demo matrices, must be equal size
A = randi(4,5,4);
B = randi(6,5,4);
C = B;
C(A<B) = A(A<B) ;

More Answers (0)

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!