Search code examples
stringmatlabmatrixcell-array

How to convert a cell array of strings into a matrix of strings?


I have a cell array of strings 763x6 cell. I want to convert this cell array into a matrix of strings to be able to use strsplit function which accepts a string as input. Any help? NOTE: When I try to use cell2mat I got an error Error using cat Dimensions of matrices being concatenated are not consistent The content of my cell array looks like this:

'pla pla pla' 'pla pla pla' 'pla pla pla' 'pla pla pla' 'pla pla pla' 'pla pla pla'

'pla pla pla' 'pla pla pla' 'pla pla pla' 'pla pla pla' 'pla pla pla' 'pla pla pla'

'pla pla pla' 'pla pla pla' 'pla pla pla' 'pla pla pla' 'pla pla pla' 'pla pla pla'


Solution

  • Rather than turning into a matrix you can just operate on the cell array since it seems like you have different-sized data in each element which makes it nearly impossible to combine into a character array:

    1. Use cellfun to call strsplit on each entry

      out = cellfun(@strsplit, data, 'uniformoutput', false);
      
    2. Just use regexp to split the string which automatically accepts cell array inputs

      out = regexp(data, '\s+', 'split');
      

    Personally, I prefer the second approach and as @excaza pointed out in the comments, strplit calls regexp internally anyhow.