MATLAB Answers

0

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

Asked by Savan Rangegowda on 13 Sep 2019
Latest activity Edited by per isakson
on 17 Sep 2019 at 10:09
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

  0 Comments

Sign in to comment.

1 Answer

Answer by per isakson
on 17 Sep 2019 at 10:05
Edited by per isakson
on 17 Sep 2019 at 10:09

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 ?

  0 Comments

Sign in to comment.