How do I find the value of a function I defined?
4 views (last 30 days)
Show older comments
Hey,
suppose I defined the function:
f1=exp(-0.2*(sqrt(0.5*((x1^2)+(x2^2)))));
after that I found the gradient of this function, and called it 'grad'
how can I find the value of grad at a certain x1,x2 values? (for example: x1=2, x2=3)
thanks
0 Comments
Answers (1)
Walter Roberson
on 7 Apr 2018
That is not a function, that is an expression that requires existing x1 and x2, and which will produce results that will amaze and confound you if x1 and x2 happen to be square arrays that are not scalar, but will fail if x1 and x2 are non-scalar but not square.
You can take the numeric gradient of an array. To evaluate that at a particular point, use interp2(). Or, in the case of positive integer coordinates, just index the array.
2 Comments
Walter Roberson
on 7 Apr 2018
Only by re-executing the expression with the changed values for x1 and x2.
You would find it easier if you changed to a function,
f1 = @(x1, x2) exp(-0.2*(sqrt(0.5*((x1^2)+(x2^2)))));
after which you could call f1(2,3) for example to evaluate the expression at that location. But you cannot take gradient of a function handle: you would need to evaluate f1 at a number of locations and take the gradient of the resulting numeric array.
If you have the symbolic toolbox, then you could
syms x1 x2
f1 = exp(-0.2*(sqrt(0.5*((x1^2)+(x2^2)))));
You can then find the gradient formula:
gr1 = gradient(f1);
which will give a vector of two symbolic expressions in symbolic variables x1 and x2. You can then evaluate those at locations:
gr1x1 = subs(gr1(1), {x1, x2}, {ArrayOfX1Values, ArrayOfX2Values});
gr1x2 = subs(gr1(2), {x1, x2}, {ArrayOfX1Values, ArrayOfX2Values});
In the special case where you are inefficiently only evaluating the gradient at one particular x1 and x2, you could
gr_x1_x2 = subs(gr1, [x1, x2], [ValueForX1, ValueForX2])
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!