How to convert non-linear equations to matrix form?

11 vues (au cours des 30 derniers jours)
Priyank
Priyank le 18 Avr 2013
Commenté : Danek le 13 Mar 2017
Hi, I am trying to represent a algebraic equation into matrix form and came across an function 'equationToMatrix' but it only converts linear equations to matrix also for a particular equation as below (x+1)(x-1) = x^2 - 1, if i want matlab to get the coefficients of the equation matlab function 'coeffs' shows [1,-1] but if i want to respresent 1*(x^2) + 0*x -1, hence the coeeficient [1,0,-1] is there a function which would decompose a equation into ascending/descending order of power and then compute its coefficient

Réponses (2)

Iman Ansari
Iman Ansari le 18 Avr 2013
Hi. Maybe sym2poly:
syms x
C=sym2poly(x^3 - 2*x - 5)
poly2sym(C)

Andy
Andy le 20 Fév 2017
Modifié(e) : Andy le 20 Fév 2017
I had a similar question, and I wrote a function which operates exactly like equationsToMatrix, but does not complain when the equations are nonlinear in your chosen variables. Hope it helps!
function [A,b] = equationsToMatrix( eq, x )
%FACTORMAT equationsToMatrix for nonlinear equations
% factors out the vector x from eq such that eq = Ax + b
% eq does not need to be linear in x
% eq must be a vector of equations, and x must be a vector of symbols
assert(isa(eq,'sym'), 'Equations must be symbolic')
assert(isa(x,'sym'), 'Vector x must be symbolic')
n = numel(eq);
m = numel(x);
A = repmat(sym(0),n,m);
for i = 1:n % loop through equations
[c,p] = coeffs(eq(i),x); % coefficients, powers of x(1)...x(n)
for j = 1:m % loop through x(1)...x(n)
for k = 1:numel(p) % loop through found powers/coefficients
if has(p(k),x(j)) % if power has the j'th variable
A(i,j) = A(i,j) + p(k)*c(k)/x(j); % add the coefficient
end
end
end
end
b = simplify(eq - A*x,'ignoreanalyticconstraints',true);
end
  1 commentaire
Danek
Danek le 13 Mar 2017
I was trying to use the method you explained. Is there anyway that you can explain how you put in the equations. I tried defining eq= and x= at the top but it's not allowing the program to run at all. Thank you

Connectez-vous pour commenter.

Catégories

En savoir plus sur Symbolic Math Toolbox dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by