How to wrap for loop around function commands and fplot?

3 views (last 30 days)
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.
  1 Comment
Emanuele Joy
Emanuele Joy on 14 May 2018
Additionally (not particularly urgent), I would like to be able to call my data set Lab6Data from its original text file instead of copy-pasting it so the code looks better. I tried something simple like call = @Lab6Data but it's not calling it as an array as it would when I copy paste it. How would I ago about accomplishing this task? What command(s) should I be aware of?

Sign in to comment.

Accepted Answer

sloppydisk
sloppydisk on 14 May 2018
Edited: sloppydisk on 14 May 2018
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);
  1 Comment
xitram
xitram on 19 Apr 2020
The above also solved a very weird problem for me, where I could draw just fine a figure with a series of plots of the same function, varying one parameter; but as soon as I "touched" the Figure (to edit or merely to resize its window), all plots but the last vanished from it...
So, thanks for the example!

Sign in to comment.

More Answers (0)

Categories

Find more on Polynomials in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!