Split a string cell array based upon a delimiter

user34790 picture user34790 · Aug 24, 2014 · Viewed 11.9k times · Source

I have a string cellarray something like this

12:34
13:45
12:45

Now I want to split this cell array into two with values separated by the delimiter. Something like this

The first one

12
13
12

and the second one

34
45
45

How can I do this in matlab?

Answer

Divakar picture Divakar · Aug 24, 2014

Input string cell array -

str_cellarr ={
    '12:34'
    '13:45'
    '12:45'}

Convert to a cell array with each cell having a 1x2 cell of split strings -

split1 = cellfun(@(x) strsplit(x,':'), str_cellarr(:),'uni',0)

Or use a more efficient solution on this as suggested by @Luis -

split1 = regexp(str_cellarr, ':', 'split')

After this you can employ two approaches.

Approach #1

Convert to a 2 element cell array with each cell containing each "set" of strings separated by the delimiter ':' -

split1_2cols = mat2cell(vertcat(split1{:}),size(str_cellarr,1),[1 1])

Finally, store each set into separate variables as the final outputs -

[var1,var2] = deal(split1_2cols{:})

Approach #2

Use each column from split1 array to get each set and store them as separate variables -

var1 = arrayfun(@(n) split1{n}(1),1:size(str_cellarr,1))' %//'
var2 = arrayfun(@(n) split1{n}(2),1:size(str_cellarr,1))' %//'

If you were looking to get char arary outputs, use char(..) to get those.