How to convert non-linear equations to matrix form?
38 views (last 30 days)
Show older comments
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
0 Comments
Answers (2)
Andy
on 20 Feb 2017
Edited: Andy
on 20 Feb 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 Comment
Danek
on 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
See Also
Categories
Find more on Calculus in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!