Graphics Programs Reference
In-Depth Information
In the above version of solve the functionreturning dx isstuck with the name
myfunc . If myfunc is replacedwith another functionname, solve will not work unless
the corresponding change is made in its code. Ingeneral, it is not agoodidea to alter
computer codethathas been tested and debugged; all data shouldbecommunicated
to a function through its arguments. MATLAB makes this possible by passing the
function handle of myfunc to solv e as an argument, as illustratedbelow.
function [x,numIter] = solve(func,x,epsilon)
if nargin == 2; epsilon = 1.0e-6; end
for numIter = 1:30
dx = feval(func,x); % feval is a MATLAB function for
x=x+dx; %evaluatingapassedfunction
if abs(dx) < epsilon; return; end
end
error('Too many iterations')
>>x=solve(@myfunc,2) %@myfuncisthefunctionhandle
x=
1.8955
The call solve(@myfunc,2) creates a function handle to myfunc and passes it
to solve as an argument. Hence the variable func in solve contains the handle
to myfunc .Afunctionpassed to another functionbyits handle isevaluatedbythe
MATLAB function
feval( function handle , arguments )
It is nowpossible to use solve to find a zeroofany f ( x ) by coding the function
x
=−
f ( x )
/
f ( x ) and passing its handle to solve .
In-Line Functions
If the functionis not overly complicated, itcan also be representedas an inline
object:
functionname
=
inline (' expression ',' var1 ',' var2 ',...)
where expression specifies the function and var1, var2, ...are the names of the inde-
pendent variables. Here is an example:
>> myfunc = inline ('xˆ2 + yˆ2','x','y');
>> myfunc (3,5)
ans =
34
Search WWH ::




Custom Search