MATLAB Answers

Halley's Comet Error

2 views (last 30 days)
Julia O'Bryant
Julia O'Bryant on 15 Dec 2019
Edited: Guillaume on 15 Dec 2019
I am converting a program from c++ to matlab. I have written this code, but keep getting an error that reads "undefined function or variable x_old". How an I fix this?
This is my code so far:
num = input('Enter a positive number: ')
acc = input('Enter convergence criterion: ')
approx = input('Enter initial apporiximation: ')
x = approx;
while abs(x-x_old)>acc
x_old = x;
y = 1/num*x*x;
x = x/8*(15-y*(10-3*y));
disp(['Square root of' num2str(num) 'is' num2str(x)])

  1 Comment

Adam Danz
Adam Danz on 15 Dec 2019
When you get to this line of code
while abs(x-x_old)>acc
how do you expect Matlab to interpret x_old since this is the first time that variable is appearing?

Sign in to comment.

Accepted Answer

Guillaume on 15 Dec 2019
Edited: Guillaume on 15 Dec 2019
"How an I fix this"
By defining x_old before using it (in the while loop)?
x_old = Inf;
while abs(x-x_old)>acc


Sign in to comment.

More Answers (0)

Sign in to answer this question.