J. Kim
J. Kim

Reputation: 105

Matlab, Comma-separated string to Cell when it has blank e.g. 1,2,3,[blank],[blank]

In Matlab,

1. strsplit('a,b,c,', ',')
2. strsplit('a,b,c,,,', ',')

both results of 1 and 2 are same,

{{'a'}, {'b'}, {'c'}, {0×0 char}}

However I want to take

{{'a'}, {'b'}, {'c'}, {0×0 char}, {0×0 char}, {0×0 char}} 

from a string

'a,b,c,,,'.

I tried 'CollapseDelimiters' option in strsplit function. But It does not work for tails.

Upvotes: 0

Views: 103

Answers (1)

matlabbit
matlabbit

Reputation: 706

As UnbearableLighness suggested, CollapseDelimiters works but you could also use split

>> strsplit('a,b,c,,,', ',','CollapseDelimiters',false)

ans =

  1×6 cell array

    {'a'}    {'b'}    {'c'}    {0×0 char}    {0×0 char}    {0×0 char}


>> split('a,b,c,,,', ',')'

ans =

  1×6 cell array

    {'a'}    {'b'}    {'c'}    {0×0 char}    {0×0 char}    {0×0 char}

I would suggest split because of the performance boost

function profFunc

    n = 1e5;

    tic
    for i = 1:n
        x = strsplit('a,b,c,,,', ',','CollapseDelimiters',false);
    end
    toc

    tic
    for i = 1:n
        x = split('a,b,c,,,', ',');
    end
    toc
end

>> profFunc
Elapsed time is 31.044903 seconds.
Elapsed time is 1.761662 seconds.

Upvotes: 1

Related Questions