how to input a function as a parameter of a function

27 ビュー (過去 30 日間)
Tony Cheng
Tony Cheng 2025 年 2 月 12 日 7:02
コメント済み: Tony Cheng 2025 年 2 月 13 日 1:58
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

採用された回答

Sam Chak
Sam Chak 2025 年 2 月 12 日 7:55
Something like this:
%% Script to call 'fMin1D'
x0 = [1, 1];
[x, fval] = fMin1D(x0, @quadfcn)
Local minimum found. Optimization completed because the size of the gradient is less than the value of the optimality tolerance.
x = 1×2
0 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
fval = 0
%% Minimizer
function [x, fval] = fMin1D(x0, fun)
[x, fval] = fminunc(fun, x0);
end
%% Quadric surface
function y = quadfcn(x)
y = x(1).^2 + x(2).^2;
end
  3 件のコメント
Sam Chak
Sam Chak 2025 年 2 月 12 日 12:55
Yes, @Tony Cheng, your understanding is correct.
Tony Cheng
Tony Cheng 2025 年 2 月 13 日 1:58
Hi Sam, thx so much for your sincere help! I make it now!

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2025 年 2 月 12 日 7:08
Use @fun as the parameter. For example
X0 = fMin1D(.5, 17, 32, 1e-10, 0.8, @fun)
  1 件のコメント
Tony Cheng
Tony Cheng 2025 年 2 月 12 日 7:29
Hi Walter, pls see the attached screenshot:
there is a red waved line under the @ symbol...

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeInterpolation についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by