Convert a Cell array with char and white spaces to Cell array with double without white spaces
조회 수: 1 (최근 30일)
이전 댓글 표시
The colums in the timetable consist of cell arrays with characters. These charachters consist of a whit space after the numbers. The figure above is for clarification.
I want to change the cell arrays with charachters and whitspaces to a cell array with doubles(only numbers) without the white spaces.
I've already tried several things as example the script below. But C only gives NaN.
A = string(weatherdata.Temperature__F);
B = deblank(A);
C = str2double(B);
Does anyone have an idea how I can solve this? Thank you very much in advance.
댓글 수: 3
Stephen23
2021년 9월 27일
편집: Stephen23
2021년 9월 27일
"The data is a csv file."
A .CSV is a simple text file whose format is defined by convention more than anything else.
What you actually uploaded is an .XLSX file, i.e. a rather complex XML-based proprietary spreadsheet file.
Nine columns of the "numeric" data are actually stored as text (replete with trailing non-breaking space character), which is the cause of your problems. Rather than messing around with trying to fix this in MATLAB, a much better solution would be to fix this badly formatted data when the spreadsheet is created.
채택된 답변
Walter Roberson
2021년 9월 27일
filename = 'https://www.mathworks.com/matlabcentral/answers/uploaded_files/750699/sample%20data.xlsx';
opt = detectImportOptions(filename, 'VariableNamingRule', 'preserve');
opt = setvartype(opt, 1, 'datetime');
opt = setvartype(opt, 6, 'categorical');
t = readtable(filename, opt);
t.Properties.VariableNames{1} = 'Date';
badcols = [3:5 7:11 13];
varnames = t.Properties.VariableNames;
for col = badcols
thisvar = varnames{col};
t.(thisvar) = str2double(regexprep(t.(thisvar), '\s+', '', 'once'));
end
t.Date = t.Date + days(t.Time);
t.Date.Format = 'MMM d, yyyy HH:mm:ss';
tt = table2timetable(t)
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Tables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!