Can someone please help me fix my while loop code?

2 views (last 30 days)
I have to create a function m file called 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.
This is my code:
function f = myfirstzero(f,a);
syms x
n = 0;
while(d >0);
Here is the sample data I have been using along with the correct answer.
myfirstzero(@(x) 2*x^3-3*x^2-12*x+6,2)
ans = 1
myfirstzero(@(x) x^3,0) ans=0
myfirstzero(@(x) x^3+2,0)
ans = 1
myfirstzero(@(x) x^6-5*x^5-2*x^4-x^3+x^2-x+10,3)
ans = 7
My code is not providing the correct answers for all of these, these are the answers my code is getting respectfully, 1,0,2,1. If someone could please let me know what is wrong with my code I would greatly appreciate it.
  1 Comment
Adam on 17 Sep 2014
It would help if you could take time to fill in the Products field for your question.
Since 'syms' I understand is part of the Symbolic Math Toolbox it would be useful to add that information as many of us do not have that toolbox.

Sign in to comment.

Accepted Answer

A Jenkins
A Jenkins on 17 Sep 2014
Since this appears to be homework, I won't give you the answer directly, but you have two bugs.
In order to see the first, you can use the debugger. Go into your editor and select the line of code where you check the while (d>0) loop, and add a breakpoint. Then run your last polynomial, where it should run through 7 times. When the debugger stops, it will be on that line, so you can go into the workspace or command window and look at your values. What is the value of n? What will the result of (d>0) be?
Once you learn how to use the debugger, you can do the same thing with the line where you update n=n+1, to help you understand what is wrong with that one.
After I fixed those two bugs, I got the correct answers for your sample data.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by