3

我一直在尝试使用以下代码来查找函数在输入是向量且函数返回标量的特定点的梯度。

以下是我尝试计算梯度的函数。

%fun.m    
function [result] = fun(x, y)
     result = x^2 + y^2;

这就是我所说的渐变。

f = @(x, y)fun(x, y);
grad = gradient(f, [1 2])

但我收到以下错误

octave:23> gradient(f, [1 2])
error: `y' undefined near line 22 column 22
error: evaluating argument list element number 2
error: called from:
error:    at line -1, column -1
error:   /usr/share/octave/3.6.2/m/general/gradient.m at line 213, column 11
error:   /usr/share/octave/3.6.2/m/general/gradient.m at line 77, column 38

我该如何解决这个错误?

4

1 回答 1

2

My guess is that gradient can't work on 2D function handles, thus I made this. Consider the following lambda-flavoring solution:

Let fz be a function handle to some function of yours

fz = @(x,y)foo(x,y);

then consider this code

%% definition part:
only_x = @(f,yv) @(x) f(x,yv);  %lambda-like stuff, 
only_y = @(f,xv) @(y) f(xv,y);  %only_x(f,yv) and only_y(f,xv) are
                                %themselves function handles

%Here you are:
gradient2 =@(f,x,y) [gradient(only_x(f,y),x),gradient(only_y(f,x),y)];  

which you use as

gradient2(fz,x,y);   

Finally a little test:

fz = @(x,y) x.^2+y.^2
gradient2(f,1,2);

result

octave:17> gradient2(fz,1,2)
ans =

    2   4
于 2012-10-31T15:35:00.893 回答