MATLAB: Plot is over plotted

iterating degree of polynomial.

%i degree for curve fitting
%j is the iterating number for subplot title
x=[1:10]
y=sin(x)
for i=10:10:100
title([' degree = ' ,num2str(i)])
for j=1:10
subplot(10,1,j)
p= polyfit(x,y,i)
x2=[1:0.01:10]
y2=polyval(p,x2)
plot(x,y,'o',x2,y2,'-b')
hold on
end
end

Best Answer

x = 1:10; % No need for square brackets
y = sin(x);
for k = 1:10
% NextPlot='add' is the same as "hold on"
AxesH(k) = subplot(10, 1, k, 'NextPlot', 'add');
end
x2 = 1:0.01:10;
for i = 10:10:100
for j = 1:10
p = polyfit(x,y,i);
y2 = polyval(p,x2);
plot(AxesH(j), x,y,'o', x2,y2,'-b');
end
end
subplot clears formerly existing axes objects. So create the axes at first and use them as parent object as first input to plot.