Import, sort and extract multiple excel files into 1 table/vector
显示 更早的评论
Hi I have 12 .csv files (1 for each month) with a fair amount of data in each, although they are presented the same way. I want to bring in all 12 files into MATLAB, and store the same 3 columns of data (columnns 2-4, rows 6-36(or end)) from each file sequentially in 3 vectors date, min, max. I have been researching and struggling all morning, and the below code is the best I have
% tell MATLAB to look for all .csv files in currently directory
files15 = dir('*.csv');
% Loop the same amount of times as number of files
for i = 1:numel(files15)
% store the file name in a column cell
x(:,i) = double(files15(i).name)
% Set a placeholder inside the file name to remove string
fNum = find((x),'TEST')
% Extract the number from the file name
out(:,i)=(fNum(fNum+5:end-4))
% sort files numerically 1-12
neworder = sort(out)
% import numbers and text as separate components for each file
[import15,import15t] = xlsread (files15);
% Store all dates in one column
d6 = import5t(7:end,2);
% Store all min and max temperatures in two columns
Tmin6 = import5(1:end,1);
Tmax6 = import5(1:end,2);
end
I think I am making it more complicated than it needs to be, any suggestions on the simplest way to achieve this?
Thanks in advance Anthony
4 个评论
Image Analyst
2018-8-19
Can you attach 2 or 3 of the files so people can try to help you?
Anthony Cook
2018-8-20
编辑:Anthony Cook
2018-8-20
dpb
2018-8-20
You'd have to modify the sscanf line a little in my posting; didn't mention about the YYYY- string before. Easy enough to do use
fmt='TEST %d-%d.csv';
and can return both values.
As a way to avoid all this grief about order, any time you create files sequentially such as this, use a format when creating the file names that includes the preceding '0's in the number fields so that the files are sorted numerically as well as lexically automagically --
fn=sprintf('TEST %d-%02d.csv',year,mo);
will produce
>> fn=sprintf('TEST %d-%02d.csv',2017,8)
fn =
'TEST 2017-08.csv'
>>
etc., and then dir will return a list of files sorted in the order desired already.
Anthony Cook
2018-8-20
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Spreadsheets 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!