how to input a function as a parameter of a function
이전 댓글 표시
Hi there,
Here I have the following recursive code fMin1D to find the local minima of a user-defined function f=fun(x).
fun(x) is able to evaluate a sample array x =[x1 … xn] and return values f =[f1 … fn] .
function x0=fMin1D(x1,xN,N,eps,x0,fun)
% samples to be scanned
Neps=1+ceil((log(xN)-log(x1))/log(1+eps));
n=max(4,min(N,Neps));
x=x1*(xN/x1).ˆ([0:n-1]/(n-1)); f=feval(fun,x);
% minimum search via direct comparison
L=f(1:n-1)<=f(2:n); I=find(L(2:n-1) & ~L(1:n-2))+1;
% recursive search or update of already found solution x0
if n<Neps, for j=1:length(I),
x0=fMin1D(x(I(j)-1),x(I(j)+1),N,eps,x0,fun); end
else x0=[x0,x(I)]; end
Since fun is also a function, how can I input it into the brackets of fMin1D as a parameter needed by fMin1D?
Many thanks!
Cheers
채택된 답변
추가 답변 (1개)
Walter Roberson
2025년 2월 12일
Use @fun as the parameter. For example
X0 = fMin1D(.5, 17, 32, 1e-10, 0.8, @fun)
카테고리
도움말 센터 및 File Exchange에서 MATLAB에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!