How to use a for-end loop to load in 6 xlsx files and plot all the data within them on one plot?
2 views (last 30 days)
Show older comments
Hello, I have done this without using a loop by repeating my data however it looks messy and is very long. The code im using is below. Do you have any suggestions on how to make it work using a for-end loop? Any help will be greatly appreciated as I am very new to Matlab.
close all
clear
clc
data2014=readmatrix('OS104BeachProfileData2014.xlsx');
xdata2014=data2014(:,1);
ydata2014=data2014(:,2);
data2015=readmatrix('OS104BeachProfileData2015.xlsx');
xdata2015=data2015(:,1);
ydata2015=data2015(:,2);
data2016=readmatrix('OS104BeachProfileData2016.xlsx');
xdata2016=data2016(:,1);
ydata2016=data2016(:,2);
data2017=readmatrix('OS104BeachProfileData2017.xlsx');
xdata2017=data2017(:,1);
ydata2017=data2017(:,2);
data2018=readmatrix('OS104BeachProfileData2018.xlsx');
xdata2018=data2018(:,1);
ydata2018=data2018(:,2);
data2019=readmatrix('OS104BeachProfileData2019.xlsx');
xdata2019=data2019(:,1);
ydata2019=data2019(:,2);
plot(xdata2014,ydata2014,'LineWidth',3);
hold on
plot(xdata2015,ydata2015,'LineWidth',3);
hold on
plot(xdata2016,ydata2016,'LineWidth',3);
hold on
plot(xdata2017,ydata2017,'LineWidth',3);
hold on
plot(xdata2018,ydata2018,'LineWidth',3);
hold on
plot(xdata2019,ydata2019,'LineWidth',3);
0 Comments
Answers (1)
Dave B
on 8 Dec 2021
Edited: Dave B
on 8 Dec 2021
I guess you have two options about how you're going to tell MATLAB about all those xlsx files - either you're going to construct the name based on the pattern (the year at the end of the filename) or you'll use dir to get a list of all the xlsx files.
Method 1: all the xlsx files in the current directory
fl = dir('*.xlsx'); % this assumes the current directory contains the xlsx files
% but that's generally a bad assumption
for i = 1:numel(fl)
data=readmatrix(fl(i).name);
plot(data(:,1),data(:,2),'LineWidth',3)
hold on
end
Method 2: using the pattern in the names
for i = 2014:2019
fn = "OS104BeachProfileData" + i + ".xlsx";
data=readmatrix(fn);
plot(data(:,1),data(:,2),'LineWidth',3)
hold on
end
0 Comments
See Also
Categories
Find more on File Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!