Convert a Cell array with char and white spaces to Cell array with double without white spaces
4 次查看(过去 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 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!