How to replace cell in a table with number?
古いコメントを表示
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'.
採用された回答
その他の回答 (1 件)
Lars Svensson
2023 年 3 月 8 日
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 件のコメント
+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
2023 年 3 月 9 日
Dear Stephen23
Thanks for the improvement!
Best,
Lars
Stephen23
2023 年 3 月 9 日
"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
2023 年 3 月 9 日
OK. Thanks.
カテゴリ
ヘルプ センター および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!