how can a symbolic derivative be vectorized automatically?

3 views (last 30 days)
Hello,
here is the simplified problem.
I have a symblic function with three arguments. And the derivative of f wrt. b
syms a b c
f = a*sin(b)*exp(c)
df = diff(f,b)
The solution is:
df = a*exp(c)*cos(b)
Now i will use this derivatve in a numeric script. And the argumetns a,b,c are vectors:
a=rand(10,1);
b=rand(10,1);
c=rand(10,1);
My current approach is to modify the derivative manualy: (adding "dots")
df = a.*exp(c).*cos(b)
Is there a way how i can change a symblic expression automatically?
My equations are has 80 or more characters and the derivatives has 2x to 3x the amount of characters.
So an automatic transform into an vectorized version would help me a lot.
Best regards,
MJ

Accepted Answer

Stephen23
Stephen23 on 20 Oct 2023
Use MATLABFUNCTION:
syms a b c
f = a*sin(b)*exp(c)
f = 
df = diff(f,b)
df = 
mf = matlabFunction(df)
mf = function_handle with value:
@(a,b,c)a.*exp(c).*cos(b)
a=rand(10,1);
b=rand(10,1);
c=rand(10,1);
mf(a,b,c)
ans = 10×1
0.8287 0.4912 0.5251 2.2295 1.7548 0.0752 1.3973 0.6642 0.1812 0.5342

More Answers (2)

Dyuman Joshi
Dyuman Joshi on 20 Oct 2023
Convert it to a function handle -
syms a b c
f = a*sin(b)*exp(c)
f = 
df = diff(f,b)
df = 
%Convert the symbolic function to an anonymous function
fun = matlabFunction(df)
fun = function_handle with value:
@(a,b,c)a.*exp(c).*cos(b)
a=rand(10,1);
b=rand(10,1);
c=rand(10,1);
fun(a,b,c)
ans = 10×1
1.6337 0.7283 1.9453 1.1977 0.0795 1.0797 0.8060 0.3090 2.5127 0.9578

Walter Roberson
Walter Roberson on 20 Oct 2023
format long g
syms a b c
f(a,b,c) = a*sin(b)*exp(c)
f(a, b, c) = 
df = diff(f,b)
df(a, b, c) = 
A = rand(10,1);
B = rand(10,1);
C = rand(10,1);
D = df(A, B, C)
D = 
vpa(D)
ans = 
double(D)
ans = 10×1
0.472553502790635 1.26659066678776 0.609162623765823 0.642273629496948 0.893411797110293 0.88743081840584 0.39637226337217 0.303468357868928 0.198740877661276 1.09526181869221

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!