In: Mechanical Engineering
create a function in matlab that sums two m x n matrices using nested loops, then returns result into a new matrix. Use nesed for loops to add matrices piece by piece. Basically means, dont program simply A+B
Function should perform error check to make sure both matrices have same number of rows/ columns.
clc;
clear all;
A=input('Enter matrix A');
B=input('Enter matrix B');
[m1 n1]=size(A);
[m2 n2]=size(B);
if(m1==m2 && n1==n2)
for i=1:m1
for j=1:n1
C(i,j)=A(i,j)+B(i,j);
end
end
fprintf('Sum of matrix A & B =');
display(C)
else
fprintf('ERROR--Size of matrix is not same . Can not perform addition')
end
TEST CODE EXAMPLE 1-------
OUTPUT1
Enter matrix A> [1 2;1 2] Enter matrix B> [1 2 3;1 2 3;1 2 3] ERROR--Size of matrix is not same . Can not perform addition
TEST CODE EXAMPLE 2
OUTPUT
Enter matrix A> [1 2 3;1 2 3;1 2 3] Enter matrix B> [3 2 1;3 2 1;3 2 1] Sum of matrix A & B =C = 4 4 4 4 4 4 4 4 4