Hot to plot a fitted line using fplot function?

1 次查看(过去 30 天)
I need to fit a straight line to a graph using fplot command. My whole code is below. It gives an error
Error using @(p,t)p(1)*t+p(2) Not enough input arguments.
Error in fplot (line 101) x = xmin; y = feval(fun,x,args{4:end});
Error in MLTD (line 8) fplot(dfit,[2 4]);
t = [0, 1.02, 1.52, 2.03, 2.55, 3.10, 3.38, 3.66, 3.80];
t = t.^2;
d = [0, 10, 20, 34, 45, 68, 80, 95, 103];
plot(t,d,'ro');
hold on;
p = polyfit(t,d,1);
dfit = @(p,t) p(1)*t+p(2);
fplot(dfit,[1,15],'b');

回答(1 个)

Star Strider
Star Strider 2015-3-1
This works:
t = [0, 1.02, 1.52, 2.03, 2.55, 3.10, 3.38, 3.66, 3.80];
t = t.^2;
d = [0, 10, 20, 34, 45, 68, 80, 95, 103];
plot(t,d,'ro');
hold on;
p = polyfit(t,d,1);
dfit = @(p,t) p(1)*t+p(2);
fplot(@(t) dfit(p,t), [1,15], 'b');
The fplot function passes only your independent variable to your function, so that has to be specified in the (in this instance) anonymous function created in the fplot argument list to represent your function, although the function itself has to ask for both arguments. Your function will pick up ‘p’ from the workspace, so fplot need only supply ‘t’.
  2 个评论
Denis Kolodyazhnyy
编辑:Denis Kolodyazhnyy 2015-3-1
Thank you a lot. Works fine but I don't quite understand the description yet, will try my best though to get the point (very new to matlab). Thanks again
Star Strider
Star Strider 2015-3-1
My pleasure!
I apologise for the delay — life intrudes.
The ‘not enough input arguments’ error results from your ‘dfit’ function requiring two arguments, ‘p’ and ‘t’, but fplot is only passing it one, that being your independent variable, since that’s how fplot works.
The key to making it work with your ‘dfit’ function is to create an anonymous function of the form:
f = @(t) dfit(p,t)
that passes only one argument to ‘dfit’ in the argument to fplot.
The rationale behind it is that your ‘dfit’ function takes two arguments, ‘p’ and ‘t’, but fplot only provides one, in this instance, ‘t’. So you create an anonymous function that only passes ‘t’ to your ‘dfit’ function. Your ‘dfit’ function picks up ‘p’ from the workspace, so fplot not only never sees it, but doesn’t care, since it’s only interested in ‘t’. Then fplot plots your function of ‘t’ against ‘t’.
This sort of construction is most frequent when you want to pass extra parameters to a specific function, for instance in nonlinear curve fitting or integrating an ODE function, but the curve fitting or ODE integration functions only want a subset of the full argument list.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Surface and Mesh Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by