Search code examples
arraysmatlabnumericcell-array

How can I convert a cell array into a numeric array in MATLAB?


I'm stuck with a supposedly simple problem in MATLAB. I have a 1x43 cell array that looks like this (note the space before each value):

labels = {' 1', ' 2', ' 3', ... , ' 43'};

And I simply want to convert it to a numeric vector of dimensions 1x43 that will look like this:

labels_numeric = [1 2 3 ... 43];

Anyone could hint me the right trick for this?


Solution

  • You can collect the individual character arrays into a single character array, then use str2num to convert it:

    labels_numeric = str2num([labels{:}]);
    

    Or even easier, just use str2double:

    labels_numeric = str2double(labels);