Search code examples
arraysstringmatlabsplitcell-array

MATLAB: how to split cell arrays of different delimiter numbers?


Assume there is an input cell:

input=

"82.3 4.3 John"

"4.2 0.0001 Tim Taylor"

This is a 2by1 cell array. I need to split this to get a 2by3 array like:

"82.3" "4.3" "John"

"4.2" "0.0001" "Tim Taylor"

The split(input) or split(input,'\t') returns error as each row of cell includes different number of delimiters.


Solution

  • You can use split, but it will differ depending on whether you have a cell array containing character vectors or a cell array containing strings (I know, it's very confusing):

    If your input is displayed like this:

    input =
    
      2×1 cell array
    
        '82.3   4.3 John'
        '4.2    0.0001  Tim Taylor'
    

    Then you have a cell array of character vectors, and you can split at the tabs like this:

    str = split(input, char(9))
    
    str = 
    
      2×3 string array
    
        "82.3"    "4.3"       "John"      
        "4.2"     "0.0001"    "Tim Taylor"
    


    If your input is instead displayed like this:

    input =
    
      2×1 cell array
    
        ["82.3  4.3 John"      ]
        ["4.2   0.0001  Tim Taylor"]
    

    Then you have a cell array of strings, and you need to concatenate the cells into a 2-by-1 array of strings before splitting at the tabs:

    str = split([input{:}].', char(9))
    
    str = 
    
      2×3 string array
    
        "82.3"    "4.3"       "John"      
        "4.2"     "0.0001"    "Tim Taylor"
    


    Note that I had to use char(9) to specify the ASCII tab character, and that the output in each case is a 2-by-3 array of strings.