Plotting large data set within for loop

7 views (last 30 days)
Erin
Erin on 10 Jun 2022
Commented: Voss on 10 Jun 2022
Hi Matlab users, can someone please help me?
I am loading in a large data set from excel, trimming it down to just the data, and plotting it in separate figures. However, I'd like to set it up in a for loop so it identifies how much data is there, and iterates through accordingly. Right now, the code looks something like this:
The data is 3200 data rows (doubles) and a varying number of columns, some of which are empty.
Here is what I have so far:
% Call data from selected file
[Filename, Data] = uigetfile('*.xlsx');
[empty, Txt]= xlsread([Data Filename]);
% Erase header and header table, record section title, remove empty cells
XSection_Name = Txt(3,1);
Txt(1:10,:) = [];
Txt_matrix = vertcat(Txt);
% Write data from cells into double array
D = str2double(Txt);
D(:,3:3:end) = [];
%Identify Array Size
[numRows , numCols] = size(D);
figure(1)
plot(D(:,1),D(:,2))
title('Cross Section 1')
figure(2)
plot(D(:,3),D(:,4))
title('Cross Section 2')
figure(3)
plot(D(:,5),D(:,6))
title('Cross Section 3')
hold off
This solution is also plotting 3 of the data sets on figure 3. Not sure why.
I have searched other threads like this and read the discussion on naming variables iteratively, but I can't seem to find a suave way to do it. Here is an example of something I tried:
for ijk = numCols
x = D(:,ijk);
y = D(:,ijk+1);
figure(1) to
plot(x,y,f)
end
Thank you kindly.

Accepted Answer

Voss
Voss on 10 Jun 2022
Edited: Voss on 10 Jun 2022
[numRows , numCols] = size(D);
for ii = 1:numCols/2
figure()
plot(D(:,2*ii-1),D(:,2*ii))
title(sprintf('Cross Section %d',ii))
end
Note that this creates new figures because the figure function is called without an argument. If you call figure with an argument, e.g., figure(3), and the specified figure already exists, then the subsequent plot calls may not clear the axes in that figure (e.g., if hold on was used). That may be the reason why you saw multiple lines being plotted in figure 3.
  2 Comments

Sign in to comment.

More Answers (1)

William Rose
William Rose on 10 Jun 2022
I admit there are some things I don;t understand about your code.
One thing I notice is that you have
for ijk=numCols...
That should be
for ijk=1:numCols...
I don't understand why you have "to" after "figure(1)".
Are you trying to plot multiple traces in a single figure? SInce "figure(1)" is inside the for loop, figure(1) will get overwritten on each pass through the loop. Put "figure(1)" before the for loop, if you want to plot multiple traces in figure 1. Also include a "hold on" command.
If you want to make numCols separate figures, then try "figure(ijk)" inside the for loop.
Perhaps you can attach the file you are loading, so that others can try to run your code.
Good luck.

Community Treasure Hunt

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

Start Hunting!

Translated by