How to convert non-linear equations to matrix form?
27 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Andy
2017-2-20
编辑:Andy
2017-2-20
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 个评论
Danek
2017-3-13
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!