Derive function handle with a vector input argument
5 views (last 30 days)
Show older comments
when I run this piece of code
q=[3 2 2 3];
f=@(p,x,y) p(1)*x.^2+p(2).*y.^2+p(3)*x.*y+p(4);
syms 'x'
df=diff(f,x);
dfdx=matlabFunction(df);
A=feval(f,q,2,2);
I get an error says
Index exceeds the number of array elements (1).
What I am trying to do is to cluster my equation coefficients into one vector to make my code compact. In my real application I have 15 coefficients. Any advice if this process is possible?
0 Comments
Accepted Answer
Walter Roberson
on 11 Jan 2024
Moved: Walter Roberson
on 11 Jan 2024
q=[3 2 2 3];
f=@(p,x,y) p(1)*x.^2+p(2).*y.^2+p(3)*x.*y+p(4);
syms p [1 4]
syms x y
df=diff(f(p,x,y),x)
dfdx = matlabFunction(df, 'vars', {p, x, y})
A = feval(f,q,2,2)
More Answers (2)
Matt J
on 11 Jan 2024
Edited: Matt J
on 11 Jan 2024
If you have the Deep Learning Toolbox, you can do automatic differentiation of vector-valued dlarrays,
p=1:15;
x0=dlarray(rand(size(p)));
[fx,gradfx] = dlfeval(@(x) somefunc(x,p),x0)
function [y,dydx]=somefunc(x,p)
y=p*x';
dydx=dlgradient(y,x);
end
0 Comments
See Also
Categories
Find more on Numbers and Precision in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!