就像标题所说,我有几个矩阵,我想在第三维堆叠。我目前有一个水平堆叠不等向量的解决方案,如下所示:
A = [1;2;3;4];
B = [1;2];
[i1,j1] = ndgrid(1:size(A,1),1:size(A,2));
[i2,j2] = ndgrid(1:size(B,1),(1:size(B,2))+size(A,2));
plane_stats = accumarray([i1(:),j1(:);i2(:),j2(:)],[A(:);B(:)]);
对于任何两个不等大小的矢量A和B(警告:我只测试了这个列向量,水平堆叠)。只要存在间隙,就会将零添加为填充,因此结果如下所示:
1 1
2 2
3 0
4 0
但是,我想把它推广到3D,所以我可以在A和B的组合后面堆叠第三个(也是不相等的)矩阵C,如下所示:
C = [1 2;3 4;5 6]
%some modification of existing ndgrid code
combo(:,:,1) =
1 1
2 2
3 0
4 0
combo(:,:,2) =
1 2
3 4
5 6
0 0
但是我不确定如何扩展我目前的解决方案。任何和所有的帮助/见解表示赞赏
答案 0 :(得分:3)
我会建议这样的事情:
给定不等大小的2D矩阵A, B, C
,
A = [1;2;3];
B = [1 2 3];
C = [1 2;3 4;5 6;7 8];
解决方案1
要在第三维堆叠,我们可以简单地执行此操作:
n_rows = max([size(A,1),size(B,1),size(C,1)]);
n_cols = max([size(A,2),size(B,2),size(C,2)]);
combo = zeros(n_rows, n_cols, 3);
combo(1:size(A,1),1:size(A,2),1) = A
combo(1:size(B,1),1:size(B,2),2) = B
combo(1:size(C,1),1:size(C,2),3) = C
解决方案2
另外,要在循环中递增地堆叠矩阵:
matrices = {A,B,C};
for i = 1:numel(matrices)
mat = matrices{i};
combo(1:size(mat,1),1:size(mat,2),i) = mat;
end
Matlab会自动为你填充零。
解决方案3
另一个没有警告的版本:
matrices = {A,B,C};
n_rows = 0; n_cols = 0;
for i = 1:numel(matrices)
mat = matrices{i};
n_rows = max(n_rows, size(mat,1));
n_cols = max(n_cols, size(mat,2));
end
combo = zeros(n_rows, n_cols, numel(matrices));
for i = 1:numel(matrices)
combo(1:size(matrices{i},1),1:size(matrices{i},2),i) = matrices{i};
end
<强>结果强>
以上所有3个解决方案都是如此:
>> combo
combo(:,:,1) =
1 0 0
2 0 0
3 0 0
0 0 0
combo(:,:,2) =
1 2 3
0 0 0
0 0 0
0 0 0
combo(:,:,3) =
1 2 0
3 4 0
5 6 0
7 8 0
答案 1 :(得分:2)
您合并A
和B
的方法完全没问题,不需要任何改进,您可以继续使用它:
A = [1;2;3;4];
B = [1;2];
[i1,j1] = ndgrid(1:size(A,1),1:size(A,2));
[i2,j2] = ndgrid(1:size(B,1),(1:size(B,2))+size(A,2));
plane_stats = accumarray([i1(:),j1(:);i2(:),j2(:)],[A(:);B(:)]);
现在...... Matlab的优点在于,只要代码需要,矩阵就会自动扩展(并填充零填充)。因此,对于给定的矩阵C
,您所要做的就是:
combo = plane_stats;
[C_m,C_n] = size(C);
combo(1:C_m,1:C_n,2) = C;
一些例子:
combo = plane_stats;
C = [1 2; 3 4; 5 6];
[C_m,C_n] = size(C);
combo(1:C_m,1:C_n,2) = C
combo(:,:,1) =
1 1
2 2
3 0
4 0
combo(:,:,2) =
1 2
3 4
5 6
0 0
combo = plane_stats;
C = [1 2; 3 4; 5 6; 7 8; 9 10];
[C_m,C_n] = size(C);
combo(1:C_m,1:C_n,2) = C
combo(:,:,1) =
1 1
2 2
3 0
4 0
0 0
combo(:,:,2) =
1 2
3 4
5 6
7 8
9 10
combo = plane_stats;
C = [1 2 3; 3 4 5; 5 6 7; 7 8 9; 10 11 12; 13 14 15];
[C_m,C_n] = size(C);
combo(1:C_m,1:C_n,2) = C
combo(:,:,1) =
1 1 0
2 2 0
3 0 0
4 0 0
0 0 0
0 0 0
combo(:,:,2) =
1 2 3
3 4 5
5 6 7
7 8 9
10 11 12
13 14 15
combo = plane_stats;
C = [1; 2];
[C_m,C_n] = size(C);
combo(1:C_m,1:C_n,2) = C
combo(:,:,1) =
1 1
2 2
3 0
4 0
combo(:,:,2) =
1 0
2 0
0 0
0 0