Passing functions in MATLAB

Hi I am having some difficulty passing functions on MATLAB and needed some help.
I am trying to implement a bisection algorithm, [l,r,nf] = bisect ( fname, a,b, tol)
Where l and r are the left and right handed end-points of the root-bracketing interval, and fname is another M-file in my directory that contains the actual function being evaluated (also an M-file)
How does one use a function as the input for an argument in MATLAB? Thanks!

回答 (1 件)

dpb
dpb 2018 年 10 月 3 日

0 投票

Look at function handles; there's a section under Data Types in the documentation...

2 件のコメント

Shakil Rafi
Shakil Rafi 2018 年 10 月 4 日
Hi so suppose I want to use @ to call the function, I am unclear what my code would look like then.
Would it be something like
[l,r,nf] = bisect (@fname, a,b,tol)
if @fname(a) * @fname(b) > 0
disp (' Function does not bracket a root');
...
or
[l,r,nf] = bisect (fname, a,b,tol)
if @fname(a) * @fname(b) > 0
disp (' Function does not bracket a root');
...
or
[l,r,nf] = bisect (@fname, a,b,tol)
if fname(a) * fname(b) > 0
disp (' Function does not bracket a root');
...
because all three of these seem to not work.
And when i want to test them out in the command window, how would i test out the function? would it be bisect(fofx,1,2,0.0001) or bisect (@fofx,1,2,0.001)
Thanks
Walter Roberson
Walter Roberson 2018 年 10 月 4 日
function [l,r,nf] = bisect ( fname, a, b, tol)
if fname(a) * fname(b) > 0
[...]
To be called with something like
[left, right, count] = bisect( @(x) sin(x).^2 - tan(x), -pi/2, pi/2, 0.01 )

この質問は閉じられています。

製品

タグ

質問済み:

2018 年 10 月 3 日

閉鎖済み:

2021 年 8 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by