0

当我help gmres在 MATLAB 中输入时,我得到以下示例:

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));

其中两个函数是:

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

function y = mfun(r,n)
    y = r ./ [((n-1)/2:-1:1)'; 1; (1:(n-1)/2)'];
end

我对其进行了测试,效果很好。我的问题是这两个函数的价值是什么,x因为我们从不给它一个?

也不应该这样写调用gmres:(y在@handle中)

x1 = gmres(@(y)afun(x,n),b,10,tol,maxit,@(y)mfun(x,n));
4

1 回答 1

1

函数句柄是在 MATLAB 中对函数进行参数化的一种方法。在文档页面中,我们找到以下示例:

b = 2;
c = 3.5;
cubicpoly = @(x) x^3 + b*x + c;
x = fzero(cubicpoly,0)

这导致:

x =
   -1.0945

那么这里发生了什么?fzero是一个所谓的函数 function,它将函数句柄作为输入,并对它们执行操作——在这种情况下,找到给定函数的根。实际上,这意味着决定要尝试fzero输入参数的哪些值以找到根。这意味着用户只需提供一个函数 - 无需提供输入 - 并将使用不同的值查询函数以最终找到根。xcubicpolyfzerox

您询问的功能gmres, 以类似的方式运行。这意味着您只需要提供一个接受适当数量的输入参数的函数,并gmres使用适当的输入调用它以产生其输出。

最后,让我们考虑一下您的调用建议gmres如下:

x1 = gmres(@(y)afun(x,n),b,10,tol,maxit,@(y)mfun(x,n));

这可能有效,也可能无效——这取决于您是否x在函数的工作区中调用了一个变量,最终调用了afunor 或mfun. 请注意,现在函数句柄接受一个输入,y但它的值在定义的函数的表达式中没有使用。这意味着它不会对输出产生任何影响。

考虑以下示例来说明会发生什么:

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.
于 2016-04-11T18:57:52.797 回答