Extracting coefficients from complicated expression

9 visualizaciones (últimos 30 días)
Lukas
Lukas el 24 de Ag. de 2025
Respondida: Deepak el 1 de Sept. de 2025
I'm trying to extract the coefficients of of an expression using the following code:
% replace exp(-i*xi) with w and expand
expr_w = expand( subs(m0(xi), exp(-1i*xi), w) );
h_k = sym(zeros(1, 2*N));
for k=1:2*N
% coefficient of w^3 corresponds to coefficient of exp(-ki*xi)
h_k(k) = sqrt(2)*feval(symengine, 'coeff', expr_w, w, k-1);
h_k(k) = vpa(h_k(k));
end
I'm replacing every instance of by w. This code works fine if m0 is simple like m0(xi) = (2^(1/2)*(exp(-xi*1i)/2 + 1/2)^2*(3^(1/2) - exp(-xi*1i) + 2))/(2*(3^(1/2) + 2)^(1/2)) but if it's more complicated like
m0(xi) =
(3*(exp(-xi*1i)/2 + 1/2)^3*(exp(-xi*2i) + 2*exp(-xi*1i)*(real((10/3 + 15^(1/2)*2i)^(1/2))/2 - 3/2) + abs((15^(1/2)*1i)/6 - (10/3 + 15^(1/2)*2i)^(1/2)/2 + 3/2)^2)^2*(exp(-xi*2i) - 2*exp(-xi*1i)*(real((10/3 + 15^(1/2)*2i)^(1/2))/2 + 3/2) + abs((15^(1/2)*1i)/6 + (10/3 + 15^(1/2)*2i)^(1/2)/2 + 3/2)^2)^2)/(2*abs((15^(1/2)*1i)/6 - (10/3 + 15^(1/2)*2i)^(1/2)/2 + 3/2)^3*abs((15^(1/2)*1i)/6 + (10/3 + 15^(1/2)*2i)^(1/2)/2 + 3/2)^3)
expr_w has some w's but there's a few that remain in the substituted expression. Hence are also in the coefficients. How can I fix this?

Respuestas (1)

Deepak
Deepak el 1 de Sept. de 2025
Hi Lukas,
My understanding according to the question posted lies in the symbolic substitution process and how to correct it to properly extract coefficients. The expression exp(-i*xi) with a new symbol w, to make the expression easier. This works for simple expressions. However, when there are complex expressions like exp(-2i*xi) or combinations of such expressions, expr_w has leftover exponential terms. As a result, when coefficients of powers of w is extracted, output is not clean.
The current approach replaces only the first exponential term and misses the higher powers like exp(-2i*xi), exp(-3i*xi) and so on.
Try adding a for loop that increments from 1 to max_k to handle all powers of the exponential term.
for k = 1:max_k expr_w = subs(expr_w, exp(-1ikxi), w^k); end
Because of this, the value will be incremented one by one and then all the higher powers will be handled well.
The code looks as below:
Hope this helps.

Etiquetas

Community Treasure Hunt

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

Start Hunting!