How to replace cell in a table with number?
Mostrar comentarios más antiguos
Hi,
I have a table and some of the cell in a table are not numbers. How to replace them with numbers so I can plot them.

So far I have managed to replace '---OF---' and 'Error' with 'NaN', but not sure how to replace e.g. '-0.6629' with -0.6629 and all NaN and 'NaN' with 0.
CSV file is in the attachment and code is below.
T = readtable('Auto_20220630100635.csv');
H = height(T);
for i = 1: width(T)
if iscellstr(T.(i))
T.(i)(strcmp(T.(i),'---O F---')) = {'NaN'};
end
end
for i = 1: width(T)
if iscellstr(T.(i))
T.(i)(strcmp(T.(i),'Error')) = {'NaN'};
end
end
Thank you in advance.
P.S.
>> T(isnan(T))=0;
Check for incorrect argument data type or missing argument in call to function 'isnan'.
>> for i= 1: width(T)
T.(i)(isnan(T.(i))) = 0;
end
Check for incorrect argument data type or missing argument in call to function 'isnan'.
Respuesta aceptada
Más respuestas (1)
Lars Svensson
el 8 de Mzo. de 2023
You may want to use
T = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/1050910/Auto_20220630100635.csv');
T1 = convertvars(T,@iscell,'string');
T2 = convertvars(T1,@isstring,'double');
T2
4 comentarios
+1 Yes, CONVERTVARS is the way to go... also in one fell swoop:
T1 = readtable('Auto_20220630100635.csv', 'VariableNamingRule','preserve')
T2 = convertvars(T1,@iscellstr,@str2double)
Lars Svensson
el 9 de Mzo. de 2023
Dear Stephen23
Thanks for the improvement!
Best,
Lars
Stephen23
el 9 de Mzo. de 2023
"Thanks for the improvement!"
I did not say improvement! My goal was just to show another option for future readers, and to give something to think about. Each approach will be suitable for different situations and data: it is quite possible that your approach is faster (string operations are highly optimised), and for someone whose text data are string type, then your approach would probably be the best. So not an "improvement", just different.
Lars Svensson
el 9 de Mzo. de 2023
OK. Thanks.
Categorías
Más información sobre Characters and Strings en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!