How to plot a cfit/plot and mutliple datasets in one subplot within a for loop?

13 views (last 30 days)
Hello,
I have mutiple datasets that are ploted within a for loop in the same subplot of a figure.
Like:
nameIndexGears = fieldnames(struct)
for i = 1:length(nameIndexGears)
subplot 211
hold on
plot(struct.(nameIndexGears{i}).data, y) %Plots the data of 4 gears in one subplot
hold off
subplot 212
plot(a,b) % plots something else
end
I also want to plot a fit in the same subplot as the data.
fitresult_1 = fit (allGears, y, 'poly1') % allGears is a concatenated Vector of all gears
nameIndexGears = fieldnames(struct)
for i = 1:length(nameIndexGears)
subplot 211
hold on
plot(struct.(nameIndexGears{i}).data, y) %Plots the data of 4 gears in one subplot
plot(fitresult_1, 'predobs') % plots the fitresults with the predictionbounds
hold off
subplot 212
plot(a,b) % plots something else
end
Ploting the fitresult does work, but sadly the ploting of the gears does not work anymore. It only plots the data of the last gear. I figured out, that in the first case matlab preprocesses the figure and then opens it. As soon as i add the cfit plot it directly opens the figure and changes it on evry loop as a consequence of which the gears overwrite themself on each repetition.
I tried various positions of my hold on and hold off comands but that doesn't change a thing. Also I tried refering to the axes in the plot line like:
subplot 211
hold on
ax1 = gca;
plot(ax1, x, y)
plot(ax1, fitresult_1, 'predobs')
hold off
Sadly the cff/plot does not support refering to a current axis.
Here are two examples of my plots:
As described i would like to have the fitted curve in the first plot.
Does anyone know a solution for this case?
Thanks in advance!
Simon

Accepted Answer

Simeon
Simeon on 20 Jan 2020
Found a "workaround" by just adding one simple if condition.
fitresult_1 = fit (allGears, y, 'poly1') % allGears is a concatenated Vector of all gears
nameIndexGears = fieldnames(struct)
for i = 1:length(nameIndexGears)
subplot 211
hold on
plot(struct.(nameIndexGears{i}).data, y) %Plots the data of 4 gears in one subplot
if i== length(nameIndexGears)
plot(fitresult_1, 'predobs') % plots the fitresults with the predictionbounds
end
hold off
subplot 212
plot(a,b) % plots something else
end
Works perfectly.

More Answers (0)

Categories

Find more on Environment and Settings in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!