How to extract the expression inside of a trig function?

6 ビュー (過去 30 日間)
Craig Atkinson
Craig Atkinson 2021 年 2 月 16 日
回答済み: Walter Roberson 2021 年 2 月 19 日
Specifically, I want to do this so that I can grab the coefficients of the expression. It's a simple conceptual question but I really have no clue how to go about it in code. Right now, I can just look at the symbolic expression in the workspace and get what I am looking for just by inspection, but I'd have to do this every time I change the variables and if I wanted to use that coefficient for anything else I would have to manually assign the value. Here's what I am trying to do:
syms x
Z = 50 - 25cos(3x+3*pi/2); % some expression obtained from other portions of code
% by inspection
Val1 = 3; % the coefficient in front of x
Val2 = 3*pi/2; % the lone coefficient
Val1 and Val2 correspond to values that I need for other calculations, and I can see them from fitting the equation to one of a general form. Is there any way to do this without having to type their values?

採用された回答

Walter Roberson
Walter Roberson 2021 年 2 月 19 日
findSymType(expression, 'cos') to extract the cos expression(s). children() to open the cos call to give you the inner expression. coeffs() to split the constant and the term.

その他の回答 (2 件)

James Tursa
James Tursa 2021 年 2 月 19 日
編集済み: James Tursa 2021 年 2 月 19 日
You could write your own simple parser for this. E.g., code for finding stuff inside the first function in the line could be:
Z = your symbolic expression
cz = char(Z);
cz(cz==' ') = [];
alphanum = false;
p = 0;
plevel = -1;
for k=1:numel(cz)
if( cz(k)=='(' )
p = p + 1;
if( alphanum && plevel == -1 )
plevel = p;
m = k;
end
end
if( cz(k) == ')' )
if( p == plevel )
cz = cz(m:k);
break;
end
p = p - 1;
end
alphanum = ismember(cz(k),['a':'z' 'A':'Z' '0':'9']);
end
c = coeffs(eval(cz));

Reshma Nerella
Reshma Nerella 2021 年 2 月 19 日
Hi,
If you want to get the coefficients of symbolic expression, you can coeffs function.
For instance,
syms x
c = coeffs(16*x^2 + 19*x + 11) %symbolic expression
c =
[ 11, 19, 16]; % coefficients of x
If you want to reverse the order of coefficients, you can use fliplr function.
Hope this helps!

カテゴリ

Help Center および File ExchangeAssumptions についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by