Fillorry
Fillorry

Reputation: 23

System of linear equations in matlab with 2 ways but can't get same results

I'm trying to solve a system of 4 linear equations in Matlab with two ways First:

A = [5,2,3,4;2,6,1,9;6,3,1,5;2,4,7,9];
B = [7;11;5;3];
X = [A\B]';

With the result:

X =  0.5556   17.4667    4.4889  -11.0444

Second:

[x,y,z,w] = solve('5*x+2*y+3*z+4*w-7','2*x+6*y+z+9*w-11','6*x+3*y+z+5*w-5','2*x+4*y+7*z+9*w-3')

With result:

X = -497/45, Y=5/9,  Z=262/15, W=202/45 

As you can see the results on the second way aren't in the correct order. I googled the equations and found that the first order is the correct one.

Has anyone an idea of what's going on and how to solve it?

Thanx in advance!

Upvotes: 1

Views: 57

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112759

Specify the order of the unknowns when you call solve:

>> syms x y z w %// define symbolic variables (unknowns)
>> [x0,y0,z0,w0] = solve('5*x+2*y+3*z+4*w-7',...
                         '2*x+6*y+z+9*w-11',...
                         '6*x+3*y+z+5*w-5',...
                         '2*x+4*y+7*z+9*w-3',...
                          x, y, z, w)
x0 =
5/9
y0 =
262/15
z0 =
202/45
w0 =
-497/45

By the way, once you have defined x, y, z, w as symbolic variables you can avoid the quotation marks:

>> [x0,y0,z0,w0] = solve(5*x+2*y+3*z+4*w-7,...
                         2*x+6*y+z+9*w-11,...
                         6*x+3*y+z+5*w-5,...
                         2*x+4*y+7*z+9*w-3,...
                         x, y, z, w)
x0 =
5/9
y0 =
262/15
z0 =
202/45
w0 =
-497/45

Upvotes: 3

Related Questions