converting cell of strings in arry or cell of numbers

I have a cell of strings 'tsince' having dimension 143 by 1 as '4632' '0.00000000' '-1440.00000000' '-1438.00000000' '-1436.00000000' '-1434.00000000' '-1432.00000000' '-1430.00000000' '-1428.00000000' . . . . '1436.00000000' '1438.00000000' '1440.00000000'
I want to convert it to an array or cell of numbers. I tried with str2num() but it gives the following error:
>> tsince2=str2num(tsince) ??? Error using ==> str2num at 33 Requires string or character array input.
I am new to matlab. somebody can please help out how to do this. Thanks in advance
Zohaib

 Réponse acceptée

Jan
Jan le 28 Déc 2011
A surprisingly efficient method even for very large input:
C = {'4632', '0.00000000', '-1440.00000000', '-1438.00000000', ...
'-1436.00000000', '-1434.00000000', '-1432.00000000' '-1430.00000000', ...
'-1428.00000000', '1436.00000000', '1438.00000000', '1440.00000000'};
S = sprintf('%s ', C{:});
D = sscanf(S, '%f');

5 commentaires

I want to thank you for an excellent and very non-intuitive answer.
I compared this approach on a Cell array of 500k length and this approach was 16 times faster than using str2double (which itself was faster than str2num/cellfun by a factor of 2).
It seems kind of crazy that using sprintf followed by sscanf is so much faster than just using str2double, but tic/toc doesn't lie ;-)
Keld Stefan Pedersen
Keld Stefan Pedersen le 22 Fév 2018
Modifié(e) : Keld Stefan Pedersen le 22 Fév 2018
Awesome. I was struggling with converting a very large cell array of strings (MxN) to numbers and this tip nailed it. Thanks a lot Jan!
Best, easy solution
clever. Thanks Jan!
I had to make my cell array a single column then ensure empties were converted to NaN (otherwise they got lost) but this worked MUCH quicker than str2double for my example, thanks Jan!
C2 = reshape(C,[],1);
C2(cellfun(@isempty,C2)) = {'NaN'};
S = sprintf('%s ', C2{:});
D = sscanf(S, '%f');
Data = reshape(D, [], size(C,2));

Connectez-vous pour commenter.

Plus de réponses (3)

Nirmal Gunaseelan
Nirmal Gunaseelan le 28 Déc 2011

0 votes

STR2NUM requires a single string to work on. You need to loop around the individual cell elements and use STR2NUM. CELLFUN is a better way of doing the same - check out the doc.
Dao Austin
Dao Austin le 17 Avr 2015

0 votes

you may convert cell to char, then use str2num:
%given A;
C=char(A);
D=str2num(C);

Catégories

En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by