# How to wrap for loop around function commands and fplot?

조회 수: 11 (최근 30일)
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이전 댓글 -1개 표시이전 댓글 -1개 숨기기
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 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이전 댓글 -1개 표시이전 댓글 -1개 숨기기
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!

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Line Plots에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by