And*_*rea 5 matlab loops matrix cell
我有一个问题,我试图解决,创建一个Nx1单元格,其中存储的数据总是N个2x2矩阵.
例:
N = 2
mycell = cell(N,1);
for i =1:N;
mycell{i} = randi([0, 10], 2);
end
newmatrix = zeros (N+1);
Run Code Online (Sandbox Code Playgroud)
所以说mycell {1}看起来像:
[3 5
2 1]
Run Code Online (Sandbox Code Playgroud)
和mycell {2}看起来像:
[6 9;
3 2]
Run Code Online (Sandbox Code Playgroud)
我新的零矩阵看起来像:
[0 0 0
0 0 0
0 0 0]
Run Code Online (Sandbox Code Playgroud)
我想让它看起来像这样(在这种对角线设置中加入第一个单元格的最后一个元素与下一个单元格的第一个元素):
[3 5 0
2 7 9
0 3 2]
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法可以做到这一点或任何可能有帮助的内置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
Run Code Online (Sandbox Code Playgroud)
使用以下步骤:
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, []));
Run Code Online (Sandbox Code Playgroud)
结果示例:
>> 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
Run Code Online (Sandbox Code Playgroud)