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!