MATLAB: How to do a linear fit on half of the data points in a set

curve fitting

I have a code that should plot a set of data points and then a linear fit to the data points. Only the second half of the data follows a linear trend so I have set the fit over the second half of the data only. I have the code
fig3 = figure;
for ij = 1:N
subplot(1,2,1);
plot(Pdissarray(ij,:)',peakposarray(ij,2:end)','.','color', CM(ij,:))
xlabel('Dissipated Power (mW)');
ylabel('Peak Wavelength (nm)');
ylim([842 855]);
hold on
fitA = polyfit(Pdissarray(ij,15:end),peakposarray(ij,15:end),1);
lambdafit = polyval(fitA,Pdiss(ij,:));
subplot(1,2,1);
plot(Pdissarray(ij,:),lambdafit,'--','color',CM(ij,:));
hold on
end
where pdissarray and peakposarray are data sets such that each row is the thing I want to plot for each iteration of the loop and there are N rows (i.e. the arrays are each Nx50 and each N represents a single data set). The plot of these data sets is great, I get a set of N lines where each is a plot of the first row of each array. The problem is the fit. I'm trying to do a polynomial fit of degree one on each one of these lines. I do polyfit followed by polyval and then plot this output but the plot of this fit is empty. What am I doing wrong? Is it an indexing problem?

Best Answer

There are several problems with the code you posted.
This works for me:
fig3 = figure;
for ij = 1:N
subplot(1,N,ij);
plot(Pdissarray(ij,:)',peakposarray(ij,2:end)','.','color', CM(ij,:))
xlabel('Dissipated Power (mW)');
ylabel('Peak Wavelength (nm)');
ylim([842 855]);
hold on
fitA = polyfit(Pdissarray(ij,15:end),peakposarray(ij,16:end),1);
lambdafit = polyval(fitA,Pdissarray(ij,:));
plot(Pdissarray(ij,:),lambdafit,'--','color',CM(ij,:));
hold off
end