フィルターのクリア

Derive function handle with a vector input argument

4 ビュー (過去 30 日間)
Majeed
Majeed 2024 年 1 月 11 日
コメント済み: Majeed 2024 年 1 月 12 日
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?

採用された回答

Walter Roberson
Walter Roberson 2024 年 1 月 11 日
移動済み: Walter Roberson 2024 年 1 月 11 日
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)
df = 
dfdx = matlabFunction(df, 'vars', {p, x, y})
dfdx = function_handle with value:
@(in1,x,y)in1(:,1).*x.*2.0+in1(:,3).*y
A = feval(f,q,2,2)
A = 31
  1 件のコメント
Majeed
Majeed 2024 年 1 月 12 日
Thank you very much!

サインインしてコメントする。

その他の回答 (2 件)

Paul
Paul 2024 年 1 月 11 日
編集済み: Paul 2024 年 1 月 11 日
Hi Majeed,
Maybe you're looking for something like this?
q = [3 2 2 3];
p = sym('p',[1 4]);
syms x y
f = p(1)*x.^2+p(2).*y.^2+p(3)*x.*y+p(4)
f = 
df=diff(f,x)
df = 
A = subs(f,[p x y],[q,2,2])
A = 
31

Matt J
Matt J 2024 年 1 月 11 日
編集済み: Matt J 2024 年 1 月 11 日
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)
fx =
1×1 dlarray 68.8215
gradfx =
1×15 dlarray 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
function [y,dydx]=somefunc(x,p)
y=p*x';
dydx=dlgradient(y,x);
end

カテゴリ

Help Center および File ExchangeNumbers and Precision についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by