Search code examples
matlabcell-array

Matlab: 2D cell array to char array


I was wondering if there is a nice way in which I can convert my 2D cell array into a 2D char matrix.

The cell array looks like this:

'test'    'me'    '0'     '22' 
'tester'  'me'    '14'    '241'
'test'    'you'   '25'    '1'  

And now I would like to put spaces between the columns and make the whole thing a char array. Meaning I want either this:

'test me 0 22    '
'tester me 14 241'
'test you 25 1   '

or this

'test   me  0   22'
'tester me  14 241'
'test   you 25   1'

Could you help me out? I tried char() but it doesn't care that the cell array is 2D and just creates one row for each element in the cell array.

EDIT: In case someone wants to get back a cell array of the concatenated rows look at this Combine Columns of Cell Array Matlab

Many thanks!


Solution

  • Well, char gets you part of the way there, and some mucking about with reshape etc. does the rest:

    out = char(C');
    out(:,end+1)=' ';
    out = reshape(out',[28,3]);
    out = out';
    

    (has perhaps more spaces in than you wanted)

    However, a better way might be to pad the internal strings in the cell array so the total length is the same in each row, then add

    f = @(x) [x,' '];
    % need at least one space after each entry
    C = cellfun(f,C,'UniformOutput',0); 
    % now work out how much extra length needed
    l = cellfun(@length,C);
    l = sum(l,2);
    l = max(l)-l;
    % pad
    for n = 1:length(l)
        C{n,end} = [C{n,end},blanks(l(n))];
    end
    

    Now all we need is:

    cell2mat(C)
    
    ans =
    
    test me 0 22      
    tester me 14 241  
    test you 25 1