aciams
aciams

Reputation: 35

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

Upvotes: 2

Views: 113

Answers (3)

Aero Engy
Aero Engy

Reputation: 3608

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

Upvotes: 1

matlabbit
matlabbit

Reputation: 706

Starting in 16b there are new text functions and the string datatype that make this easy

>> IDcell=cell(10,1);
>> IDcell(:,1)={'A123'};

>> IDcell = string(IDcell);
>> nums = extractAfter(IDcell,'A');
>> nums = double(nums)

nums =

    123
    123
    123
    123
    123
    123
    123
    123
    123
    123

Upvotes: 2

Hielke Walinga
Hielke Walinga

Reputation: 2845

You will need a loop:

n = size(IDcell,1);
IDnum = zeros(n, 1);
for i in 1:n
    IDnum(i,1) = str2num(IDcell{i, 1}(1, 2:4));
end

What you also might find interesting is cellfun

Upvotes: 0

Related Questions