vardump
vardump

Reputation: 658

Matlab function that returns gradient

I'm trying to create a function, that has two output arguments: 1. The calculated f(x) value 2. The gradient

But it's calling itself recursively all the time. What am I doing wrong?

function [y, gra] = f1(x)
y = x^2
syms z
gra = gradient(f1(z))

Thanks.

edit: Now I have this:

function [y, gra] = f1(x)
y = x^2
if nargout == 2
    syms x
    gra = gradient(f1(x))
end

edit 2:

I'm trying to use the function in the following:

[y, grad] = f1(5);
y_derived = grad(10);

Upvotes: 1

Views: 414

Answers (2)

David
David

Reputation: 8459

I think this is what you want to do:

function [y, gra] = f1(x)
f=@(x) x^2;

y=f(x); %// calculate y

syms z %// initialise symbolic variable
gra=gradient(f(z),z); %// symbolic differentiation

This will return g as a symbolic function. To calculate a value, you can use subs(gra,z,123), or, if you are going to evaluate it many times, do gradFunc=matlabFunction(gra) then gradFunc(v) where v is a vector or matrix of points you want to evaluate.

Upvotes: 1

rayryeng
rayryeng

Reputation: 104474

That's because the argument into gradient is your function name f1(z). As such, it keeps calling f1 when your original function is also called f1, and so the function keeps calling itself until you hit a recursion limit.

I think you meant to put gradient(y) instead. Try replacing your gradient call so that it is doing:

gra = gradient(y);

Upvotes: 1

Related Questions