how to substitute symbolic variables

hello ,
i want to substitute sin(theta) with theta and cos(theta) with 1 ,
the expression is like
dte1= (Ks*(474.0*te1 - 374.0*te2))/100 - 1.0*L*p*sin(te1) - 1.3*L*p*sin(1.3*te1 - 1.2*te2) - 0.3*L*p*sin(0.3*te1)
I tried "subs" function but it is replacing only the specified variable , i want to replace it like this :
for example : in the above equation i want to replace
sin(1.3*te1 - 1.2*te2) → (1.3*te1 - 1.2*te2)
sin(0.3*te1) → (0.3*te1)
summary : replace sin(theta) with theta , theta can be any symbolic variable

 Accepted Answer

Ameer Hamza
Ameer Hamza on 14 Apr 2020
Edited: Ameer Hamza on 14 Apr 2020
First convert to string. Remove sin and convert back to symbolic expression
syms K2 te1 te2 L p Ks
dte1 = (Ks*(474.0*te1 - 374.0*te2))/100 - 1.0*L*p*sin(te1) - 1.3*L*p*sin(1.3*te1 - 1.2*te2) - 0.3*L*p*sin(0.3*te1);
det1_str = string(dte1);
det1_str = strrep(det1_str, 'sin', '');
dte1 = str2sym(det1_str);

8 Comments

thanks for the reply,
but my problem is , i want to substitute sin(theta) with theta ...... theta can be anything not particuarly (1.3*te1 - 1.2*te2) or (0.3*te1) , it can be like (0.2*te2) also
Try the updated code.
thank you soo much !!!
similarly can you help me with cos(theta)=1 (entire cos(theta) substitute with 1)
That is a bit tricky. Can you give me an example expression?
dte11 = 4.74*Ks - 1.69*L*p*cos(1.3*te1 - 1.2*te2) - 0.09*L*p*cos(0.3*te1) - 1.0*L*p*cos(te1)
If the cos() function does not contain any nested brackets then the following code will replace
syms K2 te1 te2 L p Ks
dte1 = (Ks*(474.0*te1 - 374.0*te2))/100 - 1.0*L*p*cos(te1) - 1.3*L*p*cos(1.3*te1 - 1.2*te2) - 0.3*L*p*cos(0.3*te1);
dte1 = vpa(dte1);
dte1_str = string(dte1);
dte1_str = regexprep(dte1_str, 'cos\([a-zA-Z0-9\s\*\-\./]*\)', '1');
eval(['dte1=' char(dte1_str)])
However, this will fail for nested brackets, e.g., cos(2*sin(x+2)^2), there are brackets inside brackets.
Check the code for cos() -> 1 function
i got it !
TYSM !!

Sign in to comment.

More Answers (1)

mapSymType(mapSymType(dte11, 'sin', @(x) children(x)), 'cos', 1)
There might be a way to do both in one call

Categories

Community Treasure Hunt

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

Start Hunting!