如何添加3个矩阵,其中一个维度相同,所有和其他维度在matlab中不同?

时间:2017-02-14 14:35:15

标签: matlab element addition

我有矩阵A = 2x2 B = 2x4 C = 2x2我想得到一个矩阵D = 2x16例如

A=[1 3;
   2 4]
B=[3 2 4 2;
   4 3 6 3]
C=[4 5;
   7 5]
D=[(1+3+4) (1+3+5) (1+2+4) (1+2+5) (1+4+4) (1+4+5) (1+2+4) (1+2+5) (3+3+4) (3+3+5) (3+2+4) (3+2+5) (3+4+4) (3+4+5) (3+2+4) (3+2+5);
   (2+4+7) (2+4+5) (2+3+7) (2+3+5) (2+6+7) (2+6+5) (2+3+7) (2+3+5) (4+4+7) (4+4+5) (4+3+7) (4+3+5) (4+6+7) (4+6+5) (4+3+7) (4+3+5)]

表示在结果中添加行方式元素。我有一个代码,其中A = 2x1,但我可以理解如何根据A = 2x2模拟它,代码如下所示

[rows,col_B]=size(B);
[~,col_C]=size(C);
result=zeros(rows,col_B*col_C);
for i=1:col_B
    for  j=1:col_C
        result(:,(i-1)*col_C+j)=A+B(:,i)+C(:,j);
    end
end

有人可以告诉我这段代码输出RESULT的语法吗?

1 个答案:

答案 0 :(得分:1)

尝试

D = kron(A,ones(1,size(B,2)*size(C,2)))+repmat(kron(B,ones(1,size(C,2))),1,size(A,2))+repmat(C,1,size(B,2)*size(A,2))

解释:kron(Mat, ones(1,num2RepeatColumns)),重复矩阵的每一列Mat。所以"重复"两次使A = [1 2; 3 4]变为A = [1 1 2 2; 3 3 4 4],请参阅Matlab: repeat every column sequentially n times

repmat(Mat, 1, num2RepeatMatrix)复制整个矩阵,Mat和"粘贴"它紧挨着原始版本,因此A=[1 2; 3 4]变为A = [1 2 1 2; 3 4 3 4]。请参阅"水平堆栈" repmat的例子:https://www.mathworks.com/help/matlab/ref/repmat.html

<强> OLD

D=[];
for ii=1:size(A,2)
    D=[D,A(:,ii)+kron(B,ones(1,size(C,2)))+repmat(C,1,size(B,2))];
end