2017-09-15 145 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{:}].';