MATLAB: Symbolic équation factorisation : how to identify automatically the factor in front one variable and put it into a variable

factorisationMATLABsymbolic

Hello,
I have a system of very long symbolic equations with many different symbolic variables which could be factorized that way:
B1=A11*V1+A12*V2+.....+A1n*Vn
:
Bm=Am1*V1+Am2*V2+.....+Amn*Vn
The coefficients Aij are a sum and multiplication of different symbolic variables and I would like to extra it to put it in a symbolic array. Is there a matlab function that I don,t know of capable of doing this?
Thank you for your time, Rémy
PS: Here is a simple example: The two equations I could have :
a=e*c*V1-c*V2+d*V1+f
b=d*e*V2+e*V1+f*d*V1+e*f*V2+e
I would like to be able to identify automatically the factors in front of Vi and put them into an array such as:
B(1)=a-f
B(2)=b-e
A(1,1)=e*c+d
A(1,2)=-c
A(2,1)=e+f*d
A(2,2)=d*e+e*f

Best Answer

syms a b c d V1 V2 x
E1 = b*c*V1-c*V2+d*V1+b;
E2 = d*x*V2+a*V1+b*d*V1+a*b*V2+a;
E3 = d*b*V2 + c; %suppose V1 coefficient is 0?
eqns = [E1;E2;E3];
neqns = length(eqns);
vars = [V1;V2];
nvars = length(vars);
A = zeros(neqns, nvars + 1, 'sym');
extvars = [sym(1); vars];
for eqidx = 1 : neqns
[P,Q] = coeffs(eqns(eqidx), vars);
[tf, exvidx] = ismember(Q, extvars);
A(eqidx, exvidx(tf)) = P(tf);
end
B = A(:,1);
A = A(:,2:end);