Search code examples
stringmatlabtype-conversioncell-array

How do I convert from cell array to numerical values in MATLAB


I want to convert the numeric values inside a string that is stored in a cell array to a numerical array.

Like this:

IDcell=cell(10,1);
IDcell(:,1)={'A123'};
IDnum(1:size(IDcell,1),1)=str2num(IDcell{:, 1}(1,2:4));

The last part is the problem. What is possible is:

IDnum(1,1)=str2num(IDcell{1, 1}(1,2:4));

but not the whole array at once.

Thanks a lot, smaica


Solution

  • The other answers here will work. Matlabbit's use of string will work if you are running a relatively new version of Matlab. Hielke's loops or use of cellfun is how I would usually do something like this. However, here is an alternative purely because there always seems to be multiple ways to solve something in Matlab.

    >> IDchar = char(IDcell);
    >> nums= str2num(IDchar(:,2:4))
    
    nums=
    
       123
       123
       123
       123
       123
       123
       123
       123
       123
       123