Home > Enterprise >  How do I program a function that takes two matrices A and B as input and outputs the product matrix
How do I program a function that takes two matrices A and B as input and outputs the product matrix

Time:09-27

How do I program a function that takes two matrices A and B as input and outputs the product matrix A*B? Using MATLAB, with loops and conditionals.

My attempt:

function prodAB=MultiplicoMatrices(A,B)

prod=0;

prodAB=[];

for i=1:length(A)

    for j=1:length(B)

        prod=prod A(i,j)*B(j,i);

    end

    prodAB(i,j)=prod;

    prod=0;

end
A =

     1     2
     3     4

 B=[5 6 ; 7 8]

B =

     5     6
     7     8
>> prodAB=MultiplicoMatrices([1 2; 3 4],[5 6; 7 8])

prodAB =

     0    19
     0    50

CodePudding user response:

You mean the triple-loop algorithm? You could write the function as follows.

function prodAB = MultiplicoMatrices(A,B)
prodAB = zeros(size(A,1),size(B,2));
for i = 1:size(A,1)
    for j = 1:size(B,2)
        prod = 0;
        for k = 1:size(A,2)
            prod = prod   A(i,k) * B(k,j);
        end
        prodAB(i,j) = prod;
    end
end
end

Now test it,

A = [1 2; 3 4];
B = [5 6; 7 8];
MultiplicoMatrices(A,B)
ans =
    19    22
    43    50
A * B
ans =
    19    22
    43    50

so, it works.

  • Related