How to wrap for loop around function commands and fplot?

8 vues (au cours des 30 derniers jours)
Emanuele Joy
Emanuele Joy le 14 Mai 2018
Commenté : xitram le 19 Avr 2020
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 commentaire
Emanuele Joy
Emanuele Joy le 14 Mai 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?

Connectez-vous pour commenter.

Réponse acceptée

sloppydisk
sloppydisk le 14 Mai 2018
Modifié(e) : sloppydisk le 14 Mai 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 commentaire
xitram
xitram le 19 Avr 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!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Line Plots dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by