简体   繁体   English

如何编写一个 function 以两个矩阵 A 和 B 作为输入并输出乘积矩阵 A*B?

[英]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?如何编写一个 function 以两个矩阵 A 和 B 作为输入并输出乘积矩阵 A*B? Using MATLAB, with loops and conditionals.使用带有循环和条件的 MATLAB。

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。

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.所以,它有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果AB = C,给定A,B,C为矩阵,如何使用Matlab从B和C计算A? - If A.B = C, given A,B,C are matrices, how do I calculate A from B and C using Matlab? 取两个矩阵之间的距离。 R(D)中的E(i,j)= dist(A(i),B(i))。 如何制作距离矩阵 - Taking the distance between two matrices. E(i,j) = dist(A(i),B(i)) in R^D. How can I make a distance matrix 如果有两个矩阵a和b,a(b)在matlab中做了什么? - If there are 2 matrices a and b, what does a(b) do in matlab? 如何将矩阵A的每一列乘以矩阵B的每一行,并在Matlab中求和矩阵? - How to multiply each column of matrix A by each row of matrix B and sum resulting matrices in Matlab? 如何将正弦波函数用作状态空间模型的输入(对于B矩阵),并且仅获得一个图? - How to use a sinewave function into a state space model as an input (for the B matrix) and get only ONE plot? 如何创建一个将矩阵作为输入的函数? - How to create a function that takes a matrix as an input? 如何在 scilab 中将矩阵的奇数行和偶数行提取到两个单独的矩阵中? - How do I extract the odd and even rows of my matrix into two separate matrices in scilab? [ab] = cholcov函数针对对称正定矩阵返回a = []和b = NaN - [a b]=cholcov function returns a=[] and b=NaN for a symmetric positive definite matrix 如何在AX = B类型的Matlab中求解线性系统,其中矩阵B的每个元素都是子矩阵? - How can I solve a linear system in Matlab of the type AX = B, where each element of the matrix B is a submatrix? 如何在matlab中选择两个矩阵乘积的前几个元素并将其存储到另一个矩阵中 - how to select the first few elements of product of two matrices and store it to another matrix in matlab
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM