Coeff & constants of a symbolic equation

syms a b c
exp=[-a-2*b-3*c+2, 4*b-c, -5*a+3]
I need the coefficient matrix in the form
% Coef_matrix=[ -1, -2, -3, 2; 0, 4, -1, 0; -5, 0, 0, 3];
How do I get this?
I can get the first line from the following syntax (from a previous blog), but there is an error when I try to do the second & third lines (i.e. j=1:3) as there is a 'zero' which it wont recognize
xx = symvar(exp) %find the variables in expression 'exp'
Coef_matrix = zeros(numel(exp),numel(xx));
for j = 1
[v1,v2] = coeffs(exp(j),xx);
Coef_matrix(j,ismember(xx,v2)) = v1(1:numel(xx));
end
And when I get the coefficients, I cant get the constant term at the end.
The solution should be able to scale up for more variables, as this is a simplified version of my problem. Thanks

 채택된 답변

Oleg Komarov
Oleg Komarov 2012년 8월 20일
편집: Oleg Komarov 2012년 8월 20일

0 개 추천

syms a b c
exp = [-2*b-a-3*c+2; -c+4*b; -5*a+3];
xx = symvar(exp);
Coef_matrix = zeros(numel(exp),numel(xx)+1);
for j = 1:3
[v1,v2] = coeffs(exp(j),xx);
[idx,loc] = ismember(v2,xx);
idx(end) = true;
loc(loc == 0) = 4;
Coef_matrix(j,loc) = v1(idx);
end

댓글 수: 6

Mech Princess
Mech Princess 2012년 8월 20일
편집: Mech Princess 2012년 8월 20일
Thanks, it works for the symbols.
-1 -2 -3
0 4 -1
-5 0 0
How do I get the constant term at the end?
-1 -2 -3 2
0 4 -1 0
-5 0 0 3
Thanks in advance
Azzi Abdelmalek
Azzi Abdelmalek 2012년 8월 20일
편집: Azzi Abdelmalek 2012년 8월 20일
why don't you change your expression
syms a b c d
exp = [-2*b-a-3*c+2*d; -c+4*b; -5*a+3*d]
then just ignore d
Mech Princess
Mech Princess 2012년 8월 20일
편집: Mech Princess 2012년 8월 20일
Thanks. This seems great if it was a straight fwd Qn. I dont have control of the immediate expression. My actual problem is way more complicated.
"exp" is the derivative of another expression "LD_new".
LD_new is arrived at by substituting expression "st" in "LD".
LD is arrived at by summing all the expressions of "LD0".
LD0 is my input vector multiplied by the variables.
Is there an easier way to do this? Thanks again
Oleg Komarov
Oleg Komarov 2012년 8월 20일
@Mech: I edited the code to generate the coeff matrix with the constant term as well.
Mech Princess
Mech Princess 2012년 8월 20일
Thanks a million. I've been working on this for weeks!
Oleg Komarov
Oleg Komarov 2012년 8월 20일
You weren't far from the solution.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Mathematics에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by