Search code examples
matlabcell-array

Convert cell string with commas and spaces to vector


I tried to convert the cell x:

x(1,:) = {'35,35, ,35'}; 
x(2,:) = {'40,40,30,40'};
x(3,:) = {'10, , ,'};

to a matrix with:

R = cell2mat(cellfun(@str2num,x,'un',0));

but the outcome omits the first row:

 R =

    40    40    30    40

but I was expecting:

 R =

    35    35     0    35
    40    40    30    40
    10     0     0     0

How can this be done? thanks!


Solution

  • Split x by ,, convert to double using str2double and fill the missing values with 0 as follows:

    R = fillmissing(str2double(split(x,',')),'constant',0);
    
    >> R
    R =
       35   35    0   35
       40   40   30   40
       10    0    0    0
    

    Note: Avoid using str2num since it is implemented using eval. Read the security considerations and unintended side effects of using that in the documentation for details.