Pass a function as argument Matlab6.1

조회 수: 3 (최근 30일)
David Daminelli
David Daminelli 2019년 5월 25일
답변: Walter Roberson 2019년 5월 25일
Hello! I'm studing matlab and I get some problem with a code.
First, I've created f1.m:
function y = f1(x)
y = exp(x) - pi;
end
Then, I built a code to find the roots by bisector method:
function [root, err, n] = bissect(f, a, b, errMax)
m = (a+b)/2;
err = (b-a)/2;
n = 0;
while err > errMax
if f(a)*f(m) > 0
a = m;
else
b = m;
end
m = (a+b)/2;
err = (b-a)/2;
n = n + 1;
end
root = m;
end
But, when i run
>> [r,err,n] = bissect(@f1, 1, 2, 0.1);
it returns:
Warning: Subscript indices must be integer values.
>In C:\matlabR12\work\Codigo\bissect.m at line 12
??? Index exceeds matrix dimensions.
Error in ==> C:\matlabR12\work\Codigo\bissect.m
On line 12 ==> if f(a)*f(m) > 0
What am I doing wrong? I'm using Matlab R12

답변 (1개)

Walter Roberson
Walter Roberson 2019년 5월 25일
Looking at an old document https://web.stanford.edu/class/ee254/software/using_ml.pdf it appears that in R12, function handles existed, but that you needed to use feval() with them, such as
if feval(f,a)*feval(f,m) > 0

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품


릴리스

R12.1

Community Treasure Hunt

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

Start Hunting!

Translated by