How to solve Gaussian elimination related problem with Matlab?

402 Views Asked by At

How to solve $Ax = b$ for $x$ using MATLAB?

Here, $A$ and $b$ are $2 \times 2$ and $2 \times 1$ matrices, respectively.

2

There are 2 best solutions below

1
On BEST ANSWER

At least two ways:

An efficient way, using the backslash operator:

A=[2 3;4 5];
B=[5;9];
x=A\B

An understandable way using the inverse operator:

A=[2 3;4 5];
B=[5;9];
x=inv(A)*B

Remarks :

1) one could wonder why the first way has been "invented". It is based on an underlying powerful operator that is Singular Value Decomposition.

2) In order to prove the superiority of the first way, consider the following test program using for $A$ a so-called badly conditionned matrix, i.e., a $10 \times 10$ Cauchy matrix (https://fr.mathworks.com/help/matlab/ref/gallery.html#f84-1019317):

 n=10;d=1:n;
 format long
 A = gallery('cauchy',d) 
 B = rand(n,1);
 x1 = A\B;
 x2 = inv(A)*B;
 [A*x1-B,A*x2-B]

giving the result:

  0.0001410390  -809667.7086449716
  0.0000565449  -722438.2827040752
 -0.0000093213  -652220.2758271924
 -0.0001190553  -594468.2991760621
  0.0000055107  -546127.6640417306
  0.0001690775  -505068.0495135397
 -0.0000654472  -469757.8192716851
 -0.0001023717  -439067.2352784582
 -0.0000410084  -412144.6118040089
 -0.0001132063  -388335.6571490339

where we see how different $A*x_2$ is from $B$, whereas $A*x_1$ remains close to $B$...

0
On

In Matlab the general matrix equation $Ax = b$ can be solved by the Matlab commmand x = A\b; but that solver doesn't use Gaussian elimination. However it's a good way to check your answer. But here's a link to a numerical methods text that uses matlab. Page 72 introduces Gaussian Elimination and on p.74 or 75 there's code in there that you can just copy and paste into a function in matlab. Should work out. But you should just try writing how you would do the solving by hand, and then think about how you would program each step of that, your method should be nearly identical to the one from the book.