matlab - 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 函数可能会有所帮助?
谢谢你。
解决方案
这是一个基于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
使用以下步骤:
- 使用适当的交错构建行和列索引;
- 连接元胞数组并线性化,使所有数据都在一个列向量中;
- 应用于
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
推荐阅读
- r - R代码调试:未创建循环中的命名值
- python - 将变量设置为 None 会释放内存吗?
- spring - 如何在 Spring Batch 的 application.properties 中设置 cron 表达式?
- assembly - 下面的代码是否真的在汇编中实现了LCG算法
- c++ - 使用 C++ 复制构造函数初始化基类;并使用复制运算符返回对左值的引用
- javascript - 将 JS 条件简化为 if else
- import - 在我当前的项目中使用我其他仓库中的 Stenciljs 组件
- php - 如何在 AWS linux AMI 上使用 Nginx 设置 Laravel
- php - Codeigniter 给出了一个未找到的 URL
- python - 如何为 django-tables 2 使用每列搜索表单的下拉列表?