【问题标题】:cell with multiple column to matrix in MatlabMatlab中具有多列矩阵的单元格
【发布时间】:2016-09-09 16:23:46
【问题描述】:

我在 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];

你能帮帮我吗? 提前致谢

【问题讨论】:

    标签: matlab cell


    【解决方案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
    

    【讨论】:

    • 非常感谢,我有一个问题。一个单元格的每一行中的元素数量可能包含超过 2 个元素。事实上,在我的代码中包含您的出色代码,我收到此消息错误:“下标分配维度不匹配”。你能帮帮我吗?
    • @Noris 不能根据你的实际问题修改吗?此外,您没有提到在超过 2 个元素的情况下您的预期输出是什么!我只能根据你提供的信息来回答!
    猜你喜欢
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多