In: Advanced Math
The command C = max(A,B) compares corresponding values in the A and B matrices assuming they are the same size. The problem is that MATLAB’s native version does not tell you from which matrix it found the largest value. Write a new function (in MATLAB) [C,from_which] = max_new(A,B) that also output a matrix, the same size as the inputs, with either 1’s or 2’s depending on from which matrix the larger value was found. Include a live script that tests your solution.
MATLAB Script:
close all
clear
clc
A = [1 2; 3 4]
B = [3 1; 2 5]
[C, from_which] = max_new(A, B)
function [C, from_which] = max_new(A, B)
if size(A) == size(B)
from_which = zeros(size(A));
C = zeros(size(A));
for i = 1:size(A,1)
for j = 1:size(A,2)
if A(i,j) > B(i,j)
from_which(i,j) = 1;
C(i,j) = A(i,j);
else
from_which(i,j) = 2;
C(i,j) = B(i,j);
end
end
end
else
error('Invalid operation. Matrices are of different sizes.')
end
end
Live Script Screenshot: