Get the coefficient of a monomial from a longer monomial in a polynomial

조회 수: 12 (최근 30일)
Zack
Zack 2021년 3월 31일
답변: Arjun 2025년 6월 3일
Hello, I need to decompose a polynomial to a row vector and a column vector, like Ax = B, where x and B are known, A is the coefficient matrix of elements in x.
My problem is that I have a polynomial like:
row = sin(a1)*sin(a2)*sin(a5) + sin(a4)
I tried to use coeffs() to get the coefficient of sin(a3), the desired result should be 0, but coeffs() will never return the exact coefficient of the monomial. Is there a method that I can get the exact coefficient of a certain monomial(like sin(a3), sin(a1)*sin(a2))?

답변 (1개)

Arjun
Arjun 2025년 6월 3일
Hi @Zack,
I understand that you want to extract coefficient of terms from an expression.
When working with symbolic expressions in MATLAB that involve complex trigonometric terms, directly extracting the coefficient of a specific term using functions like "coeffs()" can be challenging. This is because "coeffs()" is primarily designed for polynomials and may not handle trigonometric expressions in the way we intuitively expect.
However, a practical and effective workaround is to use the two outputs of the "coeffs()" function:
  1. The first output is an array of coefficients.
  2. The second output is an array of the corresponding symbolic terms.
By leveraging this structure, we can:
  1. Define the target term we want to find the coefficient for.
  2. Search for this term in the terms array.
  3. If the term is found, retrieve its corresponding coefficient from the coefficients array using the same index.
  4. If the term is not found, we can safely assume its coefficient is zero.
Kindly refer to the code section below for implementation of the above approach:
function coeff_value = getCoeff(expr, target)
% Get coefficients and terms
[c, t] = coeffs(expr);
% Initialize result
coeff_value = sym(0);
% Search for the target in the terms array
idx = find(arrayfun(@(x) isequal(simplify(x), simplify(target)), t));
% If found, get the corresponding coefficient
if ~isempty(idx)
coeff_value = c(idx);
end
end
syms a1 a2 a3 a4 a5
expr = sin(a1)*sin(a2)*sin(a5) + 4*sin(a4);
target1 = sin(a3);
target2 = sin(a4);
coeff1 = getCoeff(expr, target1);
disp(['Coefficient of ', char(target1), ':']);
Coefficient of sin(a3):
disp(coeff1);
0
coeff2 = getCoeff(expr, target2);
disp(['Coefficient of ', char(target2), ':']);
Coefficient of sin(a4):
disp(coeff2);
4
I hope this helps!

카테고리

Help CenterFile Exchange에서 Polynomials에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by