Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Octave: Compute Gradient of a Multi-Dimensional Function at a particaular point

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?

like image 881
Hashken Avatar asked Sep 01 '25 10:09

Hashken


1 Answers

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
like image 87
Acorbe Avatar answered Sep 03 '25 22:09

Acorbe