How to extract coefficients of custom variables in symbolic expression in MATLAB?

20 ビュー (過去 30 日間)
FAISAL ALQARNI
FAISAL ALQARNI 2023 年 7 月 25 日
コメント済み: Chunru 2023 年 7 月 26 日
I want to extract the coefficient of i_B from the attached symbolic experession called omega_B and call it p for example, how to do that?
  2 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 7 月 25 日
Hello @FAISAL ALQARNI, can you post the whole code?
FAISAL ALQARNI
FAISAL ALQARNI 2023 年 7 月 25 日
I found a way to achieve this using Symbolic substitution subs
Since the expression is already factored in i_B, j_B and k_B, the coefficient of any of these symbolic variables can be simply extracted by setting its value to 1 and setting the other variables to 0 using subs
Example:
Extracting the coefficient of i_B from a symbolic expression called omega_B and call it p
syms psi phi theta i_B j_B k_B psi_dot phi_dot theta_dot
omega_B = (phi_dot - psi_dot*sin(theta))*i_B + (theta_dot*cos(phi) + psi_dot*cos(theta)*sin(phi))*j_B + (psi_dot*cos(phi)*cos(theta) - theta_dot*sin(phi))*k_B
omega_B = 
p = subs(omega_B,[i_B,j_B,k_B],[1,0,0])
p = 
Please let me know if there is a better approach.

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

採用された回答

Paul
Paul 2023 年 7 月 25 日
編集済み: Paul 2023 年 7 月 25 日
syms psi phi theta i_B j_B k_B psi_dot phi_dot theta_dot
omega_B = (phi_dot - psi_dot*sin(theta))*i_B + (theta_dot*cos(phi) + psi_dot*cos(theta)*sin(phi))*j_B + (psi_dot*cos(phi)*cos(theta) - theta_dot*sin(phi))*k_B
omega_B = 
[c,t] = coeffs(omega_B,i_B)
c = 
t = 
p = c(t == i_B)
p = 
Get all the components simultaneously. Using both output arguments of coeffs forces the first output argument to be in the desired order (at least I think that's how it works)
clear c t
[omega,t] = coeffs(omega_B,[i_B j_B k_B])
omega = 
t = 
p = omega(1); q = omega(2); r = omega(3); % if individual components are needed as individual variables
[p;q;r]
ans = 
[p,q,r]=struct('omega',num2cell(omega)).omega % one line approach
p = 
q = 
r = 

その他の回答 (1 件)

Chunru
Chunru 2023 年 7 月 25 日
編集済み: Chunru 2023 年 7 月 25 日
Let iB=1, jB=0 and kB=0. Then compute omegaB.
  3 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 7 月 25 日
Not a function let, but the english word 'let'.
He suggested the exact thing you found out on your own (what you mentioned in a comment above).
Using subs to substitute and obtain value is what Chunru meant by computing.
Chunru
Chunru 2023 年 7 月 26 日
Exactly.

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

カテゴリ

Help Center および File ExchangeSymbolic Math Toolbox についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by