【问题标题】:Combine Columns of Cell Array Matlab合并元胞数组Matlab的列
【发布时间】:2014-03-15 00:52:02
【问题描述】:

我有一个具有动态行大小和列大小的二维元胞数组。一个例子:

cell3 = [{'abe' 'basdasd' 'ceee'}; {'d' 'eass' 'feeeeeeeeee'}]

给出:(尺寸为 2 x 3)

'abe'    'basdasd'    'ceee'       
'd'      'eass'       'feeeeeeeeee'

我希望能够组合这些列并重现一个聚合字符串单元格数组,其中每个字符串由一个空格分隔。知道该怎么做吗?

所以我正在寻找的输出是:

'abe basdasd ceee'       
'd eass feeeeeeeeee'

最终尺寸为 2 x 1。

这可能吗?

【问题讨论】:

    标签: matlab


    【解决方案1】:

    在循环中或通过cellfun 应用strjoin。后者:

    >> cellRows = mat2cell(cell3,ones(size(cell3,1),1),size(cell3,2));
    >> out = cellfun(@strjoin,cellRows,'uni',0)
    out = 
        'abe basdasd ceee'
        'd eass feeeeeeeeee'
    

    【讨论】:

    • +1。你可以使用strcat 避免循环,如果不介意让事情复杂一点
    【解决方案2】:

    没有循环的解决方案或cellfun

    [m n] = size(cell3);
    cellCols = mat2cell(cell3,m,ones(1,n)); %// group by columns
    cellColsSpace(1:2:2*size(cell3,2)-1) = cellCols; %// make room (columns)...
    cellColsSpace(2:2:2*size(cell3,2)-1) = {{' '}}; %// ...to introduce spaces
    %// Note that a cell within cell is needed, because of how strcat works.
    result = strcat(cellColsSpace{:});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      • 2012-01-19
      • 1970-01-01
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多