How to wrap for loop around function commands and fplot?

8 ビュー (過去 30 日間)
Emanuele Joy
Emanuele Joy 2018 年 5 月 14 日
コメント済み: xitram 2020 年 4 月 19 日
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 件のコメント
Emanuele Joy
Emanuele Joy 2018 年 5 月 14 日
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?

サインインしてコメントする。

採用された回答

sloppydisk
sloppydisk 2018 年 5 月 14 日
編集済み: sloppydisk 2018 年 5 月 14 日
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 件のコメント
xitram
xitram 2020 年 4 月 19 日
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!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLine Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by