How can i do this "Bisection"?
显示 更早的评论
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 个评论
Walter Roberson
2018-10-9
What difficulty are you having?
HAE SIK woo
2018-10-9
Torsten
2018-10-9
You must assign the solution to the return variable xc.
Jan
2018-10-9
@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.
回答(1 个)
Jan
2018-10-9
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 个评论
HAE SIK woo
2018-10-11
编辑:Walter Roberson
2018-10-11
Walter Roberson
2018-10-11
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'
类别
在 帮助中心 和 File Exchange 中查找有关 Graphics Objects 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!