How do I fix this error with function handle?

Hello,
I've been trying to work through this problem:
Write function myfirstzero(f,a) which takes two inputs:
f: A function handle which you may assume will represent a polynomial.
a: A real number.
Does: Uses a while loop to find the smallest n such f(n)(a) = 0. Note that this means the nth derivative at x = a and note that n = 0 is fair game, where the 0th derivative of a function is just the function itself.
Returns: This value of n.
And my attempt is:
function myfirstzero(f,a)
syms x
n = 0;
d = subs(f(x), a)
while d > 0
d = diff(f(x))
n = n + 1
if d ~= 0
f = matlabFunction(d)
d = f(a)
end
end
n + 1
However, when i put in the input like myfirstzero(@(x) x^3, 2), the function will run fine until it works to d = 6, which I want the function to stop, but it keeps running because d ~= 0, then it errors.
How do I fix this?
Thank you so much, Sea

 Accepted Answer

while (d > 0) && (d <= 6)

6 Comments

Sea’s ‘Answer’ moved here:
That doesn't solve the problem :/
My error. Sorry. I intended:
while (d > 0) && (n < 6)
That should work.
It still doesn't work because as I put in x^3 for function handle, we only need to do derivative 4 times for x^3 to be zero right? so as x^3 reach 6(x^0) then this line:
f = matlabFunction(d)
makes
f = @()6.0
and thats where the error comes in because the next line wont work.
Sorry if I explained that a little unclear earlier.
Thanks though! :) Please help me solve this problem =3=
This took some diving into some functions I don’t usually use, especially in this context, but this works:
function f = myfirstzero(f,a)
syms x
n = 0;
d = subs(f(x), a)
while (d > 0) && (n < 6)
d = diff(f(x))
n = n + 1
if d ~= 0
f = matlabFunction(d)
fv = func2str(f)
ep = strfind(fv,'()')
if ~isempty(ep)
break
end
d = f(a)
end
end
The trick here is to convert ‘f’ into a string and then search for parentheses with nothing in them. If that’s ‘true’, the break out of the iteration and return ‘d’ as the output. I tested it to with x^8 and it seemed to perform as I believe you want it to. I don’t know what (if anything) you want to return as output, so I leave that to you. I opted to return ‘f’.
Works great! Thank you so much! I will take a look it detail and learn the new commands and functions you used here so I can solve this kind of problem in the future.
Thank you so much for your time!
My pleasure!
( The sincerest expression of appreciation here MATLAB Answers is to Accept the Answer that most closely solves your problem. )

Sign in to comment.

More Answers (0)

Asked:

Sea
on 11 Sep 2014

Commented:

on 23 Feb 2020

Community Treasure Hunt

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

Start Hunting!