Next: 5. Data analysis
Up: 4. Linear algebra
Previous: 4.1 Basic operations
  Contents
In MATLAB matrix algebra is defined only for vectors and matrices. There
are many cases in computational physics where we need to use matrix
algebra. A common example is solving a system of simultaneous
equations. For example consider the following equations of three variables.
In matrix notation, we can rewrite the problem as
as
follows.
The solution is made by taking the inverse of
to give
Linear systems like this are easy to solve in MATLAB using the left
division operator, \. Do this example.
% Solving a linear system
A = [3 2 -1
-1 3 2
1 -1 -1]
y = [10 5 -1]' % Note the use of the traspose operator!
x = A\y % x should now contain the solution
% if that's true A*x should give back 'y'
A*x
MATLAB gives
which we can verify is the correct answer by
trying
and seeing that it yields the original
. Note that
in this example we used the matrix multiplication operator * (not .*). This
time it worked because the number of columns in
is equal to the number
of rows in
.
An alternative way to solve the problem is to use the inverse of
directly, as shown below.
% Solving a linear system using the inverse of A
x = inv(A)*y % x should now contain the solution
% If that's true A*x should give back 'y'
A*x
This approach may seem more straightforward but it requires more CPU time
since the inverse of
must be computed, whereas in the first approach
MATLAB doesn't have to find the inverse directly. While CPU time is not an issue
for our small examples, it can become the most important issue for large
problems.
Several special functions also exist for finding the dot product, cross
product and norm of vectors. Doing the example below should be sufficiently
instructive.
% Dot, cross, and all that
v = [1 0 -1]
w = [2 1 1]
dot(v,w)
cross(v,w)
cross([1 0 0], [0 1 0]) % i.e., i x j = k
dot(v,v)
norm(v) % length of v, i.e, sqrt(v.v)
Next: 5. Data analysis
Up: 4. Linear algebra
Previous: 4.1 Basic operations
  Contents
Gus Hart
2005-01-28