How to convert all the rows containing char values to numbers in a table without for loop?

3 vues (au cours des 30 derniers jours)
Hi All,
I have a table containing 1360 rows and 50000 columns. Rows from 17 until end are actually numbers but stored as 'char'. Is there any way to convert from char to numbers without a for loop?
I tried using cellfun inside a for loop and it takes forever.
for ii = 1:size(table,2)
table{17:end, ii} = cellfun(@str2num, table{17:end, ii}, 'UniformOutput', false);
end
example table looks like this -
var1 var2 var3 var4 var5 ... var50000
'56' '' '56' '' '0' ... ........
'56' '' '56' '' '0' ... ........
'' '56' '56' '' '0' ... ........
'' '56' '56' '' '56'... ........
'' '56' '56' '56' '56'... ........
Any help is appreciated, thank you al in advance.
Regards,
Savan

Réponses (1)

per isakson
per isakson le 17 Sep 2019
Modifié(e) : per isakson le 17 Sep 2019
Replacing str2num by str2double might help. str2num uses eval(), which is slow. str2double takes arrays as input.
%%
cac = repmat( {'1.2'}, 1,5e4 );
tic, num = str2double( cac ); toc
str = repmat( "1.2", 1,5e4 );
tic, num = str2double( str ); toc
shows
Elapsed time is 0.539569 seconds.
Elapsed time is 0.614483 seconds.
and
>> tic, num = cellfun( @str2num, cac, 'uni',true ); toc
Elapsed time is 0.963888 seconds.
Thus str2double it will at best take forever/2. I hoped for a bigger difference.
You use 'UniformOutput',false shouldn't it be true ?

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by