导入数据
在实时编辑器中打开导入数据任务。在文件字段中输入第一个电子表格的文件名 01_weather.xlsx。
要查看此任务生成的代码,请点击任务参数区域底部的显示代码展开任务显示。
% Set up the Import Options and import the data
opts = spreadsheetImportOptions("NumVariables", 12);
% Specify sheet and range
opts.Sheet = "3179575";
opts.DataRange = "A2:L32";
% Specify column names and types
opts.VariableNames = ["STATION", "NAME", "LATITUDE", "LONGITUDE", "ELEVATION", "DATE", "AWND", "PRCP", "SNOW", "TAVG", "TMAX", "TMIN"];
opts.VariableTypes = ["categorical", "categorical", "double", "double", "double", "datetime", "double", "double", "double", "double", "double", "double"];
% Specify variable properties
opts = setvaropts(opts, ["STATION", "NAME"], "EmptyFieldRule", "auto");
% Import the data
x01_weather = readtable("
% Clear temporary variables
clear opts生成的代码分成几个步骤,并用注释提供文档说明。进行以下更改以自动导入所有 12 个月的电子表格:
创建一个 yearWeather 表,您可以将每个月的电子表格中的数据追加到该表中。
创建一个包含表示每个月的字符串的 namePrefixes 向量。
使用 namePrefixes 创建一个文件名向量。使用十二个文件名的常规模式。
根据每个月的天数创建一个由若干数据范围组成的向量。在生成的代码中,范围跨 A 列到 L 列、第 2 行到第 32 行(比一月的天数大 1)。
使用 for 循环和您创建的变量导入所有文件,并将它们追加到 yearWeather 中。
% Changes #1 and #2: Create variables
yearWeather = table();
namePrefixes = ["01" "02" "03" "04" "05" "06" "07" "08" "09" ...
"10" "11" "12"];
% Set up the Import Options and sheet
opts = spreadsheetImportOptions("NumVariables", 12);
opts.Sheet = "3179575";
% Specify column names and types
opts.VariableNames = ["STATION", "NAME", "LATITUDE", "LONGITUDE", ...
"ELEVATION", "DATE", "AWND", "PRCP", "SNOW", ...
"TAVG", "TMAX", "TMIN"];
opts.VariableTypes = ["categorical", "categorical", "double", ...
"double", "double", "datetime", "double", ...
"double", "double", "double", "double", "double"];
% Specify variable properties
opts = setvaropts(opts, ["STATION", "NAME"], "EmptyFieldRule", "auto");
% Changes #3 and #4: Create vectors of filenames and data ranges
fileNames = namePrefixes + "_weather.xlsx";
dataRanges = "A2:L"+string(day(datetime(2021,1,31)+calmonths(0:11))+1);
% Change #5: Import all files and append them in yearWeather
for i = 1:length(namePrefixes)
fileName = fileNames(i);
opts.DataRange = dataRanges(i);
monthWeather = readtable(fileName, opts, "UseExcel", false);
yearWeather = [yearWeather; monthWeather];
end
% Clear temporary variables
clear opts使用导入的数据绘制 2021 年波士顿每天的低温和高温。
plot(yearWeather.DATE,[yearWeather.TMIN yearWeather.TMAX])
hold on
xlabel("Date")
ylabel("Temperature (℉)")
legend("Low Temperature","High Temperature",location="Northwest")