Split cell array of strings based on delimiter

I have a cellarray string something like this

12:34
13:45
12:45

      

Now I want to split this array of cells into two with values ​​separated by a separator. Something like that

The first

12
13
12

      

and second

34
45
45

      

How can I do this in Matlab?

+3


source to share


2 answers


The input cell array of the string is -

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

      

Convert to a cell array with each cell having a cell 1x2

separated by rows -

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

      

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

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

      

After that, you can use two approaches.

Approach # 1



Convert to a cell array 2 element

with each cell containing each "set" of rows separated by a delimiter ':'

-

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

      

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

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

      

Approach # 2

Use each column from an array split1

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 want to get char arary outputs use char(..)

to get them.

+4


source


You seem to be dealing with time. Values hours:minutes

.

In this case, the easiest way is to use the function that is created for this purpose. datevec

str = { '12:34'
        '13:45'
        '12:45'};

[~, ~, ~, H, M] = datevec(str,'HH:MM')

      

returns:

H =
    12
    13
    12


M =
    34
    45
    45

      



If yours minutes:seconds

, it works the same:

[~, ~, ~, ~, M, S] = datevec(str,'MM:SS')

      

If you need lines, push everything through num2str

, for example:

MinutesAsString = num2str(M);

      

+3


source







All Articles