plotting with function and matrix

8 views (last 30 days)
joanna zappa
joanna zappa on 7 Jan 2016
Answered: Walter Roberson on 7 Jan 2016
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?

Answers (1)

Walter Roberson
Walter Roberson on 7 Jan 2016
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.

Community Treasure Hunt

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

Start Hunting!