简体   繁体   中英

How do I program a function that takes two matrices A and B as input and outputs the product matrix A*B?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM