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

3 次查看(过去 30 天)
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

回答(1 个)

per isakson
per isakson 2019-9-17
编辑:per isakson 2019-9-17
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 ?

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by