Loop through and plot columns in excel

조회 수: 5 (최근 30일)
Alex Hentschel
Alex Hentschel 2017년 7월 11일
답변: dpb 2017년 7월 12일
I need to call from an excel sheet and assign the first two columns to X and Y variables. I use these variables in a calculation and then I need to plot them.
Then I need to loop through the next two columns in the excel sheet (columns 3+4) and assign these to X and Y and run the calculation again and then plot the results. I already have the code for the calculation so I'm just stuck on looping through the columns and the graphing. This is what I have:
filename = 'samplefile.xlsx';
File = xlsread(filename);
sheet = 1;
xlRange = 'A14:A1013';
xlRange2 = 'B14:B1013';
x = xlsread(filename,sheet,xlRange);
y = xlsread(filename,sheet,xlRange2);
- There is a variable number of columns in each file but the same number of rows.

답변 (2개)

Image Analyst
Image Analyst 2017년 7월 12일
You forgot to attach your workbook. But I'll give it a guess. Try this (untested)
filename = 'samplefile.xlsx';
data = xlsread(filename);
[rows, columns] = size(data);
for col = 1 : 2 : columns
x = data(14:1013, col);
y = data(14:1013, col + 1);
plot(x, y, '-', 'LineWidth', 2);
hold on;
end
grid on;
xlabel('X', 'FontSize', 20);
ylabel('Y', 'FontSize', 20);
title('Y vs. X', 'FontSize', 20);

dpb
dpb 2017년 7월 12일
Fuggetabout the actual columns, just read the data and iterate over however many you have...
filename = 'samplefile.xlsx';
data = xlsread(filename); % all the numeric data in the file
for i=1:2:size(data,2) % iterate over columns in steps of two...
[X,Y]=yourfunction(data(:,i),data(:,i+1)); % call function; pass x, y pair
plot(X,Y) % plot the X, Y result or however need
end
Of course, you'll want to add legend, title, etc., etc., to make plots nice and all, but that's the basics of handling the data.
If there are numeric values prior to the row 14, just set
data(1:NtoKill,:)=[]; % eliminate first NtoKill rows
after reading the sheet or, vice versa,
data=data(RowToKeep:end,:); % keep rows wanted only
ends up the same either way; take your pick. :)

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by