2017-09-15 148 views
-2

我想要找到简单的方法将包含矩阵的1x324单元阵列转换为2维矩阵。将包含矩阵的单元格转换为2d矩阵

每个单元阵列的元素都是一个大小为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]; 
+2

请了解你的[数据类型(http://uk.mathworks.com/help/matlab/data-types_data-types.html),原来的措辞在这个问题说得非常混乱!你不能有一个包含单元格的矩阵,因为矩阵只能包含数字数据。为了让未来的访问者更清楚,我编辑了你的问题,因为你没有回复澄清,但将来尽量不要模棱两可,它会鼓励更好的答案。 – Wolfie

回答

3

cell2mat函数确实如此。该DOC例如:

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

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 = reshape(B,prod(size(A{1})),numel(A)).' 
+0

我试过,但它创建了27x30456矩阵,我需要的是应该创建324x2538矩阵。 –

0

现在我找到了解决方案,如果将来有人遇到类似问题,我会在这里添加它:

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

写这个的一种方法是使用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{:}].';