# Plotting in a for loop

34 vues (au cours des 30 derniers jours)
Janna Hinchliff le 23 Jan 2019
Modifié(e) : Adam Danz le 23 Jan 2019
I have a code that reads data in a set of files and does some plots and fits on the data. The code I have at the moment is:
D = uigetdir
cd(D);
S = dir(fullfile(D,'LIV Data T= *.mat')); % Makes a structure with all files
N = numel(S); % Counts number of files
CM = cool(N); % set colormap
fig1 = figure;
for ii = 1:N
I = T.num(3:end,1); % Extract each parameter from full file and ignore first two data points - they're often dodgy
V = T.num(3:end,2);
P = T.num(3:end,3);
DataPoints = length(I);
thresh = find(P>LasingThreshold,1); % checks for when power is above threshold for fitting
fit = polyfit(I(thresh:round(DataPoints/3)),P(thresh:round(DataPoints/3)),1); %Need value of P to be greater than the laser threshold - this should be done better eventually
fitplot = polyval(fit, I); % evaluates fit as line
subplot(1,2,1);
plot(I,P,'.','markers',5,'color',CM(ii,:))
plot(I,fitplot,'-.','color',CM(ii,:))
xlabel('Current (mA)')
ylabel('Power (mW)')
hold on
subplot(1,2,2);
plot(I,V,'.-','markers',4,'color',CM(ii,:))
xlabel('Current (mA)')
ylabel('Voltage (V)')
hold on
end
This mostly works, however, the data points from the current power plot in the first loop are missing. The fit is still shown and in all of the following loops both the fit and the data points are on the graph. What is the problem with plotting the data points in the first loop?
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

Adam Danz le 23 Jan 2019
Modifié(e) : Adam Danz le 23 Jan 2019
On the first iteration of the loop, the "hold on" command isn't called until after the first plot() object is overwritten. To fix that, move the "hold on" command to the line shown below.
subplot(1,2,1);
plot(I,P,'.','markers',5,'color',CM(ii,:))
hold on %<---- move here
plot(I,fitplot,'-.','color',CM(ii,:))
xlabel('Current (mA)')
ylabel('Power (mW)')
%hold on % remove this
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Line Plots dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by