将单元格数组的单元格数组转换为矩阵矩阵 [英] Convert cell array of cell arrays to matrix of matrices
问题描述
我可以将矩阵的单元格数组转换为矩阵:
I can convert a cell array of matrices to matrix:
>> C={[1,1]; [2,2]; [3,3]};
>> cell2mat(C)
ans =
1 1
2 2
3 3
这可以.但是,我想将包含其他单元格数组的单元格数组转换为矩阵:
This is OK. But, I want to convert a cell array including other cell arrays to a matrix:
>> C={{1,1}; {2,2}; {3,3}};
>> cell2mat(C)
Error using cell2mat (line 53)
Cannot support cell arrays containing cell arrays or objects.
因此,所需的输出是:
>> mycell2mat({{1,1}; {2,2}; {3,3}})
ans =
1 1
2 2
3 3
该怎么做?
我也想对多维对象做同样的事情:
I want to do same thing for multidimensional ones also:
>> mycell2mat({{1,1;1,1}; {2,2;2,2}; {3,3;3,3}})
ans(:,:,1) =
1 1
1 1
ans(:,:,2) =
2 2
2 2
ans(:,:,3) =
3 3
3 3
推荐答案
To be honest, I never liked cell2mat
for being slow, so I've come up an alternative solution using comma-separated lists instead!
这非常简单,只需使用冒号运算符和
This is fairly simple, just use the colon operator and concatenate all vectors vertically:
C = {[1,1]; [2,2]; [3,3]};
A = vertcat(C{:})
所以我们得到:
A =
1 1
2 2
3 3
转换单元格数组的单元格
这有点棘手.由于它是单元格数组的单元格数组,因此我们必须通过两次使用冒号和 reshape
放入所需的矩阵.
Transform a cell array of cell arrays
This is a bit trickier. Since it's a cell array of cell arrays, we'll have to obtain a vector of all elements by a double use of the colon and horzcat
, and then reshape
it into the desired matrix.
C = {{1,1}; {2,2}; {3,3}};
V = [size(C{1}), 1]; V(find(V == 1, 1)) = numel(C);
A = reshape([horzcat(C{:}){:}], V)
所以我们得到:
A =
1 1
2 2
3 3
V
的操作可确保正确调整A
的形状,而不必显式指定输出尺寸(不幸的是,我没有为此找到一个衬板).这也适用于多维单元阵列:
The manipulation of V
makes sure that A
is reshaped correctly without having to specify the output dimensions explicitly (unfortunately, I didn't find a one liner for this). This also works for multi-dimensional cell arrays as well:
C = {{1, 1; 1, 1}; {2, 2; 2, 2}; {3, 3; 3, 3}};
V = [size(C{1}), 1]; V(find(V == 1, 1)) = numel(C);
A = reshape([horzcat(C{:}){:}], V)
A(:,:,1) =
1 1
1 1
A(:,:,2) =
2 2
2 2
A(:,:,3) =
3 3
3 3
PS
我认为最后一个示例的正确结果应该是6×2矩阵,而不是2×2×3.但是,这不是您所要求的,因此是不合时宜的.
P.S
I think the correct result for the last example should be a 6-by-2 matrix instead of a 2-by-2-by-3. However, that is not what you requested, so it's off-topic.
这篇关于将单元格数组的单元格数组转换为矩阵矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!