Coeff & constants of a symbolic equation

3 views (last 30 days)
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

Accepted Answer

Oleg Komarov
Oleg Komarov on 20 Aug 2012
Edited: Oleg Komarov on 20 Aug 2012
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 Comments
Mech Princess
Mech Princess on 20 Aug 2012
Thanks a million. I've been working on this for weeks!
Oleg Komarov
Oleg Komarov on 20 Aug 2012
You weren't far from the solution.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!