Reputation: 1637
I am trying to solve linear equations with many variables. So i used this to create multiple variables.
xvariables = sym('x', [n 1])
where n is the number of variables and it created a vector of variables x1 x2 x3...xn
So how do I use this vector beside syms when using linsolve instead of listing out all the variables?
% syms xvariables (something like that) instead of:
syms x2 x3 x4 x5 x6 x7 x8
eqn1 = 0.5*x2 + 0.12*x3 == 21.8;
eqn2 = 0.12*x2 + 0.5*x3 + 0.12*x4 == 21.9;
eqn3 = 0.12*x3 + 0.5*x4 + 0.12*x5 == 47.8;
eqn4 = 0.12*x4 + 0.5*x5 + 0.12*x6 == 37.6;
eqn5 = 0.12*x5 + 0.5*x6 + 0.12*x7 == 27.5;
eqn6 = 0.12*x6 + 0.5*x7 + 0.12*x8 == 52.5;
eqn7 = 0.12*x7 + 0.5*x8 == 59;
[A,B] = equationsToMatrix([eqn1, eqn2, eqn3, eqn4, eqn5, eqn6, eqn7], [x2, x3, x4, x5, x6, x7, x8])
X = linsolve(A,B)
I hope that makes sense. Thanks!
Upvotes: 0
Views: 187
Reputation: 10792
You have better to use the mldivide
operator. (symbol \
) (in my opinion!)
You have your matrix P that contains the equation:
p =
[0.50000 0.12000 0.00000 0.00000 0.00000 0.00000 0.00000;
0.12000 0.50000 0.12000 0.00000 0.00000 0.00000 0.00000;
0.00000 0.12000 0.50000 0.12000 0.00000 0.00000 0.00000;
0.00000 0.00000 0.12000 0.50000 0.12000 0.00000 0.00000;
0.00000 0.00000 0.00000 0.12000 0.50000 0.12000 0.00000;
0.00000 0.00000 0.00000 0.00000 0.12000 0.50000 0.12000;
0.00000 0.00000 0.00000 0.00000 0.00000 0.12000 0.50000]
or if you don't want to write the 0
:
p = zeros(7)
p(1,1) = 0.5;
p(1,2) = 0.12;
p(2,1) = 0.12;
...
Your vector s that contains the solution
s = [21.8,21.9,47.8,37.6,27.5,52.5,59]'
And you can resolve your system with:
>> res = p\s
res =
40.0000 %x2
15.0000 %x3
80.0000 %x...
50.0000
25.0000
75.0000
100.0000
Upvotes: 0
Reputation: 13933
When using sym('x',[n 1])
you are creating a symbolic vector with automatically generated elements [x1; x2; ...; xn]
. The elements do not directly appear in the MATLAB workspace but they are accessible by using parentheses on the created variable (xvariables
in your question, x
in my answer). Therefore we use the same syntax as with a 'normal' vector/matrix. Thus xn
can be accessed with x(n)
.
For the equations we can use a vector as well and store them in a single variable eqn
. This additionally simplifies the call to equationsToMatrix
.
This yields the following code:
x = sym('x', [7 1]);
eqn(1) = 0.50*x(1) + 0.12*x(2) == 21.8;
eqn(2) = 0.12*x(1) + 0.50*x(2) + 0.12*x(3) == 21.9;
eqn(3) = 0.12*x(2) + 0.50*x(3) + 0.12*x(4) == 47.8;
eqn(4) = 0.12*x(3) + 0.50*x(4) + 0.12*x(5) == 37.6;
eqn(5) = 0.12*x(4) + 0.50*x(5) + 0.12*x(6) == 27.5;
eqn(6) = 0.12*x(5) + 0.50*x(6) + 0.12*x(7) == 52.5;
eqn(7) = 0.12*x(6) + 0.50*x(7) == 59;
[A,B] = equationsToMatrix(eqn, x)
X = linsolve(A,B)
Upvotes: 1