2016-01-14 235 views
0

我想將單元格內容大小不同的單元格數組轉換爲矩陣。我曾嘗試下面的代碼(從previous question):單元陣列(不同大小的單元格)到矩陣

tcell = {[1,2,3], [1,2,3,4,5], [1,2,3,4,5,6], [1], []}; %# Sample array 
maxSize = max(cellfun(@numel,tcell)); %# Get the maximum vector size 
fcn = @(x) [x nan(1,maxSize-numel(x))]; %# Create an anonymous function 
rmat = cellfun(fcn,tcell,'UniformOutput',false); %# Pad each cell with NaNs 
rmat = vertcat(rmat{:})     %# Vertically concatenate cells 

我收到以下錯誤代碼:

矩陣

尺寸被連接起來並不一致。

錯誤@(x)[x,nan(1,maxSize-numel(x))]

我想我的單元陣列是從測試示例內容不同(見告訴):我的單元陣列的內容(1x31細胞)觀看在MATLAB時是

30x1 cell 40x1 cell 37x1 cell 

我必須先對我的單元格陣列進行另一次轉換嗎?我如何將我的單元格陣列轉換爲tcell的形式?

我一直在尋找一段時間,但我還不熟悉所有的術語。解決方案可以很簡單,但我還沒有知識來看它。所有投入都歡迎!

+0

你想如何連接它們?預期產出的規模是多少? –

+1

您必須在單元格內轉置您的內容。這段代碼僅適用於行向量。 – marsei

+1

@marsei有解決方案:你必須轉置單元格,或者用列向量輸出('@(x)[x; nan(...)]')編寫匿名函數。 –

回答

0

我發現下面的答案多虧了評論家的輸入:

A = cellfun(@transpose,Arad,'UniformOutput',false); %transpose the cell array 
maxSize = max(cellfun(@numel,A)); %# Get the maximum vector size 
fcn = @(x) [x nan(1,maxSize-numel(x))]; %# Create an anonymous function rmat = cellfun(fcn,A,'UniformOutput',false); %# Pad each cell with NaNs 
rmat = horzcat(rmat{:}) ; % concatenate horizontally 
rmat = horzcat(rmat{:}) ; % concatenate horizontally again 
rmat = reshape(rmat,maxSize, []);% reshape to m(=maxsize)x n(determined by total number of elements/number of rows(maxsize) 
1

其實你原來的代碼幾乎是完美的,但對於行向量。對於單元格中的列向量,您錯過了分號。

maxSize = max(cellfun(@numel,tcell)); %# Get the maximum vector size 
    fcn = @(x) [x ; nan(1,maxSize-numel(x))]; %# semicolon here     
    rmat = cellfun(fcn,tcell,'UniformOutput',false); %# Pad each cell with NaNs