【问题标题】:Convert a cell containing matrices to a 2d matrix将包含矩阵的单元格转换为二维矩阵
【发布时间】:2017-09-15 14:11:07
【问题描述】:

我想找到一种简单的方法将包含矩阵的 1x324 元胞数组转换为二维矩阵。

元胞数组的每个元素都是一个大小为 27x94 的矩阵,因此它们包含 2538 个不同的值。我想将此矩阵元胞数组转换为 324x2538 矩阵 - 其中输出的行包含来自元胞数组的每个矩阵(作为行向量)。


要阐明我的数据是什么样的以及我正在尝试创建什么,请参阅以下示例:

matrix1 = [1,2,3,4,...,94 ; 95,96,97,... ; 2445,2446,2447,...,2538]; % (27x94 matrix)
% ... other matrices are similar
A = {matrix1, matrix2, matrix3, ..., matrix324}; % Matrices are in 1st row of cell array

我想得到什么:

% 324x2538 output matrix
B = [1     , 2   ,   ..., 2538  ;  % matrix1
     2539  , 2540,   ..., 5076  ;  % matrix2
     ...   
     819775, 819776, ..., 822312]; 

【问题讨论】:

  • 请了解你的data types,这个问题的原始措辞让人很困惑!您不能拥有包含单元格的矩阵,因为矩阵只能包含数字数据。我已经编辑了您的问题,以便将来的访问者更清楚地了解您的问题,因为您没有回答澄清,但在将来尽量不要一开始就模棱两可,它会鼓励更好的答案。

标签: matlab matrix cell


【解决方案1】:

cell2mat 函数正是这样做的。文档示例:

C = {[1],    [2 3 4];
     [5; 9], [6 7 8; 10 11 12]};
A = cell2mat(C)
A = 

     1     2     3     4
     5     6     7     8
     9    10    11    12

你现在有了你的矩阵,所以只需修改它以包含行:

B = rand(27,302456); % your B
D = reshape(B,27,94,324); % stack your matrices to 3D
E = reshape(D,1, 2538,324); % reshape each slice to a row vector
E = permute(E,[3 2 1]); % permute the dimensions to the correct order
% Based on sizes instead of fixed numbers
% D = reshape(B, [size(A{1}) numel(A)]);
% E = reshape(D,[1 prod(size(A{1})) numel(A)]);
% E = permute(E,[3 2 1]); % permute the dimensions to the correct order

或者,将其从您的B 中插入一行:

B = reshape(B,prod(size(A{1})),numel(A)).'

【讨论】:

  • 我试过了,但它会创建 27x30456 矩阵,我需要的是创建 324x2538 矩阵。
【解决方案2】:

编写此代码的一种方法是使用cellfun 对单元格的每个元素进行操作,然后将结果连接起来。

% Using your input cell array A, turn all matrices into column vectors
% You need shiftdim so that the result is e.g. [1 2 3 4] not [1 3 2 4] for [1 2; 3 4]
B = cellfun(@(r) reshape(shiftdim(r,1),[],1), A, 'uniformoutput', false);
% Stack all columns vectors together then transpose
B = [B{:}].';

【讨论】:

    【解决方案3】:

    现在我找到了解决方案,如果以后有人遇到类似问题,我会在这里补充:

    for ii = 1:length(A)
        B{ii} = A{ii}(:);
    end
    B = cell2mat(B).';
    

    【讨论】: