matlab,用户将矩阵输入变量

时间:2014-04-18 05:25:48

标签: matlab matrix

我有matlab的代码来乘法矩阵如何让用户添加矩阵然后在代码中使用矩阵?

例如[n,m] =输入(此处为用户输入矩阵)

  [n,m] = size(A);
[p,q] = size(B);
C = zeros(n,p);

if p~=m
    error('Inner Matrix Dimensions Must Agree.')
end

for k = 1:n
    for j = 1:q
        temp=0;
        for i = 1:p
            temp = temp+(A(k,i)*B(i,j));
        end
        C(k,j) = temp;
    end
end

1 个答案:

答案 0 :(得分:0)

您可以在脚本中使用:

A = input('input array A ');
B = input('input array B ');

[n,m] = size(A);
[p,q] = size(B);
C = zeros(n,p);

if p~=m
    error('Inner Matrix Dimensions Must Agree.')
end

for k = 1:n
    for j = 1:q
        temp=0;
        for i = 1:p
            temp = temp+(A(k,i)*B(i,j));
        end
        C(k,j) = temp;
    end
end

或者您可以将上述内容编写为函数:

function C = matrixmultiply(A,B)

[n,m] = size(A);
[p,q] = size(B);
C = zeros(n,p);

if p~=m
    error('Inner Matrix Dimensions Must Agree.')
end

for k = 1:n
    for j = 1:q
        temp=0;
        for i = 1:p
            temp = temp+(A(k,i)*B(i,j));
        end
        C(k,j) = temp;
    end
end

end