MATLAB: How to wrap for loop around function commands and fplot

anonymousanonymous functionfor loopfplotMATLABplotpolyfitpolyval

So I'm writing a script that fits a polynomial and plots a given a set of data and I figured out how to do it for a chosen degree (e.g. 2nd degree), but I'm trying to clean it up and make it iterate for 2nd degree, 3rd degree, and 4th degree.
Here is my current script: https://pastebin.com/cwTySwA3
As you can see, I separated each iteration into its own line of code and the code works perfectly fine as it is right now. I tried to change the coeff2, coeff3, coeff4 lines to:
for k = 2:4, coeff(k) = polyfit(xData, yData, k);
which I assumed would have worked, but it gave me an error "Unable to perform assignment because the indices on the left side are not compatible with the size of the right side." With just coeff = polyfit…, it just gives plots the last value of k and gives me the plot for the 4th degree polynomial.
I think it's the polyfit function that's stopping me, and I don't know how to clean it up. Help would be appreciated, thank you.

Best Answer

I would choose to store the functions and labels in cells as follows:
n = 3;
range = 1:n;
coeff = cell(n, 1);
anonFunc = cell(n, 1);
labels = cell(n+1, 1);
labels{1} = 'Data';
hold on
for i = range
coeff{i} = polyfit(xData, yData, i+1);
anonFunc{i} = @(x) polyval(coeff{i},x);
fplot(anonFunc{i},[xMin,xMax]);
labels{1+i} = ['Degree ', num2str(i+1)];
end
title('Fit');
xlabel('t'); ylabel('y');
legend(labels);