How to replace two symbolic variables with two (1x3) arrays and result in a (1x3) array?
5 views (last 30 days)
Show older comments
I am trying to do an analytic derivation of a long expression and then plug the numerical values in once the derivation is done. I've given a simplified example below. The problem that I am having is that it returns a (1x9) array instead of a (1x3) array.
Is there a command to replace multiple variables at once? Right now, I have only figured out how to replace one at a time which might be causing the array issue. Additionally, is there a way to have the numerical values calculated immediately? It works with a one variable replacement, but once I add more variables, the expressions are not evaluated.
% r and s arrays that will replace x and y
r = [1 2 3] ;
s = [10 20 30] ;
% defining x and y as symbolic variables
x = sym('x','real') ;
y = sym('y','real') ;
% derivative of y*sin(x) wrt x
dx = diff(y.*sin(x),x) ;
% replacing symbolic x with r array (in dx)
dx1 = subs(dx,["x"],r) ;
% replacing symbolic y with s array (in dx1)
dxf = subs(dx1,["y"],s)
0 Comments
Answers (1)
Sulaymon Eshkabilov
on 7 Feb 2023
There are a few different ways to get it done. One of the possible ways is the next one:
% r and s arrays that will replace x and y
r = [1 2 3] ;
s = [10 20 30] ;
% defining x and y as symbolic variables
x = sym('x','real') ;
y = sym('y','real') ;
% derivative of y*sin(x) wrt x
dx = diff(y.*sin(x),x) ;
for ii=1:3
Dxy1(ii,:) = (subs(dx, [x, y], [r(ii), s(ii)]));
end
Dxy1
%% Alt. Way
syms f(x,y)
f(x,y) = y*sin(x);
dF = diff(f(x,y), x)
for ii=1:3
Dxy2(ii,:) = subs(dF, [x, y], [r(ii), s(ii)]);
end
Dxy2
0 Comments
See Also
Categories
Find more on Linear Algebra in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!