# Solving System of Equations

5 views (last 30 days)
Erkin Karatas on 11 Nov 2019
Commented: Fabio Freschi on 11 Nov 2019
Hi all,
I want to solve equations, when I know the number of equations, this is how I normally do
%
syms a b c d
eqn1 = 13*a -2.5*b == 8;
eqn2 = -10.5*a + 13*b - 2.5*c == 8;
eqn4 = -10.5b + 2*c + 3*d == 8;
[A,B] = equationsToMatrix([eqn1, eqn2, eqn3, eqn4], [a, b, c, d])
X = linsolve(A,B)
I want to modify this format(if possible) into the unkown equations, for example for 10 equations or 20. Since the number of equations can change, I cannot write them as shown above. If it's not possible, is there any other way to solve these unknown number of equations which are dependent each other?
%Modified??
n=10;
syms a b c d e x y z %number of variables can change as the number of equations change, so no idea what to write here
eqn1 = 13*a -2.5*b == 8;
eqn2 = -10.5*a + 13*b - 2.5*c == 8;
eqn3 = -10.5*b + 13*c -2.5*d == 8;
eqn4 = -10.5*c + 13*d - 2.5*e == 8;
...
eqnn = -10.5x + 2*y + 3*z == 8;
[A,B] = equationsToMatrix([eqn1, eqn2, eqn3], [x, y, z]) %?
X = linsolve(A,B)

Fabio Freschi on 11 Nov 2019
It seems you are solving a numeric system of equations. Why don't you simply put the coefficient matrix in A and the right-hand-side in an array b and use backslash?
% case 1
A = [13 -2.5 0 0;
-10.5 13 -2.5 0
1 1 1 1 % dummy values: equation 3 is missing in your code
0 -10.5 2 3];
b = [8
8
8 % dummy value
8];
x = A\b;
You can scale it to as many equations you like, and it is definitely faster than symbolic calulations

Erkin Karatas on 11 Nov 2019
I am trying to write a code about CFD node analysis, so the number of equations change when we change the number of nodes and the actual equations are way longer this one, and I cannot write the coefficients because they depend on other calculations, I just wrote the coefficients just to make the code simpler.
Fabio Freschi on 11 Nov 2019
It is about 15 years that I write numerical formulations for electromagnetics. You should build your coefficient matrix filling the entries using your calculations (based on FEM, FDM, ...) and then using
x = A\b;
To solve the final system. BTW: using standard discretization of PDE, you will have a sparse coefficient (stiffness) matrix. It may be of help having a look at the sparse command and the use of sparse matrices in Matlab
Fabio Freschi on 11 Nov 2019
To go further in the details, the stiffness matrix is usually built as
for i = 1:Nelements % loop over elements
Aloc = zeros(Nnodes) % preallocation
for j = 1:Nnodes % loop over nodes og th i-th elem
for k = 1:Nnodes % loop over nodes og th i-th elem
end
end
... % map local matrix to global matrix A
end
Even if there are many examples to avoid some or all these loops.

Jeremy Marcyoniak on 11 Nov 2019
Typically I prefer doing it numerically by putting my equations into the form
Ax=b
and then
x = A\b