Search code examples
matlabcell-array

Create new matrix of cell arrays


I have a Cell Array 1x254 with data of this type:

data = {'15/13' '14/12' '16/13' '16/13' '16/14' '17/14' '17/14' '18/14' '19/15'};

the first number corresponds to the temp, the second number the temp2

I need to separate the data and insert them in a matrix :

B =

    15    13
    14    12
    16    13
    16    13
    16    14
    17    14
    18    14
    19    15

I tried to use this solution

data = regexp(tempr, '\W','split');
B=cell2mat(cat(3,data{:}));

but I find no way to get ahead....

could give me a hint?


Solution

  • You are pretty close. You can do it using regexp as you did, but with / as the delimiter, in addition to cellfun(which is just a loop really) to convert from strings to digits, then apply cell2mat to get a numeric array as output:

    clc
    clear
    
    data = {'15/13' '14/12' '16/13' '16/13' '16/14' '17/14' '17/14' '18/14' '19/15'};
    
    %// Split data
    C = regexp(data, '/', 'split');
    
    %// Convert from strings to double
    D = cellfun(@str2double,C,'uni',0);
    
    %// Get final numeric matrix
    E = cell2mat([D(:)])
    

    NOTE:

    As pointed out by Luis Mendo, str2double operates on cell arrays so you can trade cellfun and cell2mat for this single line:

    E = str2double(vertcat(C{:}))
    

    Output:

    E =
    
        15    13
        14    12
        16    13
        16    13
        16    14
        17    14
        17    14
        18    14
        19    15