plotting with function and matrix

조회 수: 5 (최근 30일)
joanna zappa
joanna zappa 2016년 1월 7일
답변: Walter Roberson 2016년 1월 7일
I have created this function
function y=polyfun(x,p)
y=cos(sqrt(abs(polyval(p,x)))) - sin(x)/2;
end
and I need to plot it from -0.5 to 0.5 so I wrote
pf=@polyfun;
fplot(pf,[-0.5 0.5])
Error using polyfun (line 2)
Not enough input arguments.
Error in fplot (line 101)
x = xmin; y = feval(fun,x,args{4:end});
it says error why?

답변 (1개)

Walter Roberson
Walter Roberson 2016년 1월 7일
Your polyfun requires two inputs. Your pf takes a handle to that directly, so pf will be a handle to a function that expects two inputs. You then call fplot() which is documented as
The function must be of the form y = f(x), where x is a vector whose range specifies the limits, and y is a vector the same size as x and contains the function's value at the points in x (see the first example). If the function returns more than one value for a given x, then y is a matrix whose columns contain each component of f(x) (see the second example).
We can see that the function is expected to take only one input, so fplot() is only going to be trying to pass one input. But your function needs two inputs so it is going to fail.
What you need is to have defined your polynomial, such as
x = sort(rand(1,10)); %some arbitrary data
y = sort(rand(1,10));
p = polyfit(x, y, 4); %create polynomial coefficients
and then ensure that this p is passed into polyfun:
pf = @(x) polyfun(x, p);
and then you can
fplot(pf, [-0.5 0.5])
Notice that the function handle being passed to pf only expects one input, and it takes that one input and expands it into a call to polyfun providing a pre-set value p for the second input to polyfun . fplot is happy because the function it called only needed one argument, and polyfun is happy because it received two arguments.

카테고리

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