2016-09-09 46 views
2

我在Matlab中有一個單元格,其組成如下,其中每個條目可以有多個整數。 例如:在Matlab中有多列到矩陣的單元格

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

A{2,1}=[5]; 
A{2,2}=[3]; 
A{2,3}=[1]; 
A{2,4}=[5]; 
A{2,5}=[2]; 
A{2,6}=[6]; 
A{2,7}=[2]; 
A{2,8}=[2]; 
A{2,9}=[1]; 
A{2,10}=[5 4]; 

我會得到包含細胞的元素的矩陣。當單元格中的行包含多個條目(例如A {1,2})時,應該包含條目(所有條目)一次。例如矩陣輸出應該是:

B=[5 5 5 5 5 5 5 5 5 5; %A{1,:}first column in the cell 
    5 7 5 5 5 5 5 5 5 5; %A{1,:}first column and the second element in row  
         A{1,2} 
    5 3 1 5 2 6 2 2 1 5; 
    5 3 1 5 2 6 2 2 1 4]; 

你能幫我嗎? 在此先感謝

回答

1

這將做到這一點:

[r,c]= size(A); %Finding the size of A for the next step 
B=zeros(r*2,c); %Pre-allocating the memory 
for iter=1:r 
    k=find(cellfun('length',A(iter,:))==2); %finding which elements have length =2 
    temp=cell2mat(A(iter,:)); %converting cell to matrix 
    k1= k+ [0:size(k,2)-1];  %finding which elements should come in the next row instead of in next column 

    temp1= temp(k1+1);   %storing those elements in 'temp1' matrix 
    temp(k1+1)=[];    %removing those elements from original 'temp' matrix 

    B(2*(iter-1)+1:2*(iter-1)+2, :)=[temp; temp]; 
    B(2+(iter-1)*2,k)=temp1; %replacing the elements from temp1 
end 
B 
+0

非常感謝,我有一個問題。單元格每行內的元素數量可能包含2個以上的元素。實際上,在我的代碼中包含您的優秀代碼時,我收到此消息錯誤: 「訂閱分配維度不匹配」。 你能幫我嗎? – Noris

+0

@Noris你不能根據你的實際問題修改它嗎?此外,你沒有提到你的期望輸出將會是超過2個元素的情況!我只能根據你提供的信息來回答! –