首页 > 解决方案 > Matlab:将单元格中的矩阵对角附加到一个新的零矩阵中

问题描述

我有一个我正在尝试解决的问题,它创建了一个 Nx1 单元,其中存储的数据始终是 N 个 2x2 矩阵。

例子:

N = 2
mycell = cell(N,1); 
for i =1:N;
    mycell{i} = randi([0, 10], 2);
end 

newmatrix = zeros (N+1); 

所以说 mycell{1} 看起来像:

[3 5
 2 1]

和 mycell{2} 看起来像:

[6 9;
 3 2]

我的新零矩阵如下所示:

[0 0 0
 0 0 0
 0 0 0]

我也想让它看起来像这样(在这种对角线设置中,将第一个单元格的最后一个元素与下一个单元格的第一个元素连接起来):

[3 5 0
 2 7 9
 0 3 2]

有没有一种简单的方法可以做到这一点或任何内置的 Matlab 函数可能会有所帮助?

谢谢你。

标签: matlabloopsmatrixcell

解决方案


这是一个基于accumarray. 它不使用循环,它适用于通用大小N(矩阵数)、R(每个矩阵的行数)和C(每个矩阵的列数):

生成示例数据(使用问题中代码的概括):

N = 3; % number of matrices
R = 2; % number of rows of each matrix
C = 3; % number of columns of each matrix
mycell = cell(N,1); 
for i =1:N;
    mycell{i} = randi([0, 10], [R C]);
end

使用以下步骤:

  1. 使用适当的交错构建行和列索引;
  2. 连接元胞数组并线性化,使所有数据都在一个列向量中;
  3. 应用于accumarray构建结果矩阵,对具有相同索引的值求和。

代码:

indCol = repmat((0:N-1)*(R-1)+(1:R).', C, 1);
indRow = repelem((0:N-1)*(C-1)+(1:C).', R, 1);
newmatrix = accumarray([indCol(:) indRow(:)], reshape(cat(3, mycell{:}), 1, []));

示例结果:

>> celldisp(mycell)
mycell{1} =
     3     1     2
     5     6     7
mycell{2} =
     7     4     2
     8     0    10
mycell{3} =
     1     5     0
     9    10     4
>> newmatrix
newmatrix =
     3     1     2     0     0     0     0
     5     6    14     4     2     0     0
     0     0     8     0    11     5     0
     0     0     0     0     9    10     4

推荐阅读