4

I have been trying out the following code to find the gradient of a function at a particular point where the input is a vector and the function returns a scalar.

The following is the function for which I am trying to compute gradient.

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

This is how I call gradient.

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

But I get the following error

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

How do I solve this error?

Acorbe
  • 8,367
  • 5
  • 37
  • 66
Hashken
  • 4,396
  • 7
  • 35
  • 51

1 Answers1

3

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
Acorbe
  • 8,367
  • 5
  • 37
  • 66
  • 1
    informative answer, I've only just started to use Octave. loving all this vectorized stuff :) – zeffii Oct 31 '12 at 18:52
  • @zeffii, indeed this is more kind of lambda (functional programming) stuff. But you can do a lot of vectorization either ;). – Acorbe Oct 31 '12 at 19:05
  • Thanks for the answer. I know we can write a separate script for computing gradient. But considering the fact that Octave is considered as an Open-Source alternative to MATLAB, I hoped that there should be an in-built way to compute Gradient for multi-dimensions. – Hashken Nov 02 '12 at 01:12
  • @Karthik; W: How can you achieve that using matlab without additional toolboxes (optimization)? – Acorbe Nov 02 '12 at 10:56
  • @Acorbe: I just safely assumed that MATLAB has this functionality in-built. If not, both MATLAB and Octave need to seriously think about adding this functionality. – Hashken Nov 02 '12 at 11:24
  • @Karthik, AFAIK Matlab doesn't have a built-in `gradient` function defined on function handles either. `gradient` in MATLAB is defined just on matrices. It has been a surprise to me that octave has. BTW, to my knowledge, octave produces a 1D vector out of the 1D function handle and then performs a simple `diff` command. In more than 1D there would be ambiguity on the differentiation stencil pattern. – Acorbe Nov 02 '12 at 11:32