Calling function inside function input

I've been trying to run a program that finds the root of a function following the bisection method, given an interval (a,b), tolerance level and maximum iterations for the method. I want to be able to run custom functions, but I cannot seem to find a way to figure it out. I don't know if I'm even chasing the right answer.
I have previously stated my custom function as:
function [y]=fun(x)
y=x-sin(x)-1
end
And then ran my main program like this, using the variables:
z=linspace(0,5,1000);funcion=fun(z);a=1;b=3;tol=0.0001;maxiter=5;
function [x,it]=bisecc(funcion,a,b,tol,maxiter)
for it=1:maxiter
c=(a+b)/2;
if sign(funcion(a))~=sign(funcion(c))
b=c;
else
a=c;
end
if abs(funcion(c))<tol
break
end
end
plot(linspace(a,b,length(funcion)),funcion), grid on
x=c;
[x_]=fzero(funcion,(a+b)/2);
fprintf('x(fzero)=%f',x_)
However, foolish of me, funcion(*whatever*) just indexes from the matrix that I created, and I spent an embarrasing amount of time until I noticed.
What can I do? Thanks in advance.

 采纳的回答

z=linspace(0,5,1000);funcion=fun(z);a=1;b=3;tol=0.0001;maxiter=5;
Do not do that. Instead do
a = 0; b = 5; %to match your linspace
tol = 0.0001;
maxiter = 5;
[x, it] = bisecc(@fun, a, b, tol, maxiter)
and in the function change
plot(linspace(a,b,length(funcion)),funcion), grid on
to
X = linspace(a,b,500);
plot(X, funcion(X)), grid on

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by