3

I have a 2D cell array with dynamic row sizes and column sizes. One example:

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

Gives: (with dimension 2 by 3)

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

I want to be able to combine the columns and reproduce a aggregate string cell array where each string is separated by a single white space. Any idea how to do that?

So the output i am looking for is:

'abe basdasd ceee'       
'd eass feeeeeeeeee'

The final dimension is 2 by 1.

Is this possible?

user1234440
  • 22,521
  • 18
  • 61
  • 103

2 Answers2

4

Apply strjoin either in a loop or via cellfun. The latter:

>> cellRows = mat2cell(cell3,ones(size(cell3,1),1),size(cell3,2));
>> out = cellfun(@strjoin,cellRows,'uni',0)
out = 
    'abe basdasd ceee'
    'd eass feeeeeeeeee'
chappjc
  • 30,359
  • 6
  • 75
  • 132
1

Solution without loops or 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{:});
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147