Reputation: 241
When I type help gmres
in MATLAB I get the following example:
n = 21; A = gallery('wilk',n); b = sum(A,2);
tol = 1e-12; maxit = 15;
x1 = gmres(@(x)afun(x,n),b,10,tol,maxit,@(x)mfun(x,n));
where the two functions are:
function y = afun(x,n)
y = [0; x(1:n-1)] + [((n-1)/2:-1:0)'; (1:(n-1)/2)'].*x+[x(2:n); 0];
end
and
function y = mfun(r,n)
y = r ./ [((n-1)/2:-1:1)'; 1; (1:(n-1)/2)'];
end
I tested it and it works great. My question is in both those functions what is the value for x
since we never give it one?
Also shouldn't the call to gmres
be written like this: (y
in the @handle)
x1 = gmres(@(y)afun(x,n),b,10,tol,maxit,@(y)mfun(x,n));
Upvotes: 0
Views: 1269
Reputation: 3476
Function handles are one way to parametrize functions in MATLAB. From the documentation page, we find the following example:
b = 2;
c = 3.5;
cubicpoly = @(x) x^3 + b*x + c;
x = fzero(cubicpoly,0)
which results in:
x =
-1.0945
So what's happening here? fzero
is a so-called function function, that takes function handles as inputs, and performs operations on them -- in this case, finds the root of the given function. Practically, this means that fzero
decides which values for the input argument x
to cubicpoly
to try in order to find the root. This means the user just provides a function - no need to give the inputs - and fzero
will query the function with different values for x
to eventually find the root.
The function you ask about, gmres
, operates in a similar manner. What this means is that you merely need to provide a function that takes an appropriate number of input arguments, and gmres
will take care of calling it with appropriate inputs to produce its output.
Finally, let's consider your suggestion of calling gmres
as follows:
x1 = gmres(@(y)afun(x,n),b,10,tol,maxit,@(y)mfun(x,n));
This might work, or then again it might not -- it depends whether you have a variable called x
in the workspace of the function eventually calling either afun
or mfun
. Notice that now the function handles take one input, y
, but its value is nowhere used in the expression of the function defined. This means it will not have any effect on the output.
Consider the following example to illustrate what happens:
f = @(y)2*x+1; % define a function handle
f(1) % error! Undefined function or variable 'x'!
% the following this works, and g will now use x from the workspace
x = 42;
g = @(y)2*x+1; % define a function handle that knows about x
g(1)
g(2)
g(3) % ...but the result will be independent of y as it's not used.
Upvotes: 1