How can i do this "Bisection"?
Show older comments
function myfunc = Untitled()
y=@(x) x^3-x-1;
xl=0.6;
xu=1.2;
xc=bisect(y,xl,xu);
end
function xc=bisect(y,xl,xu);
if y(xl)*y(xu) > 0
fprintf('No roots exist within the given interval\n');
return
end
if y(xl) == 0
fprintf ('x1 is one of the roots\n')
return
elseif y(xu) == 0
fprintf ('x2 is one of the roots\n')
return
end
for i=1:100
xm = (xl+xu)/2; %bisection
if y(xl)*y(xm) < 0
xu = xm;
else
xl = xm;
end
if abs(y(xl)) < 1.0E-6
break
end
end
fprintf('The roots : %f\nThe number of bisection: %d\n',x1,i)
end
4 Comments
Walter Roberson
on 9 Oct 2018
What difficulty are you having?
HAE SIK woo
on 9 Oct 2018
Torsten
on 9 Oct 2018
You must assign the solution to the return variable xc.
Jan
on 9 Oct 2018
@HAE SIK woo: You have some information about the problems in line 5 and 8. I guess, this is an error message? Then please share this important details with the forum, because this is more efficient than guessing, what the problem is.
Answers (1)
Jan
on 9 Oct 2018
Your function should reply xc:
function xc = bisect(y,xl,xu) % By the way: No semicolon needed here
I guess that the error message tells you, that xc is not defined anywhere. What about a trailing: xc = (xu + xl) / 2?
You mix "x1" (X one), "xl" (X L), "x2", "xu" and "xc". This provokes confusions.
2 Comments
HAE SIK woo
on 11 Oct 2018
Edited: Walter Roberson
on 11 Oct 2018
Walter Roberson
on 11 Oct 2018
The syntax
function f=bisect(y,xl,xu);
means that the function name is bisect and that it accepts up to three parameters, and that the calling context may expect up to one output to be returned, and that whatever is assigned inside the function to the variable f is to be made available to the caller if the caller wants it.
The syntax
f=bisect(y,xl,xu);
means that the function bisect is to be called, positionally passing in three parameters, and that a single output is expected to be returned from the function and that the value is to be assigned to the variable f inside the workspace of the function Untitled -- so, Yes, the calling function does want the returned value, and so the function bisect must assign a value to the appropriate variable (unless the called function uses error to signal an error condition.)
Now, this is a problem, because under no circumstances does your code for bisect assign a value to the appropriate variable, f.
In most of the cases in your code, you can assign either xl or xu to f before doing the return, but you need to figure out what you want to do with the case 'No roots exist within the given interval'
Categories
Find more on Graphics Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!