next up previous contents
Next: 5. Data analysis Up: 4. Linear algebra Previous: 4.1 Basic operations   Contents

4.2 Dot, Cross, Norm, Inverse, Linear solutions

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.
$\displaystyle 3x_1+2x_2-x_3$ $\textstyle =$ $\displaystyle 10$ (4.1)
$\displaystyle -x_1+3x_2+2x_3$ $\textstyle =$ $\displaystyle 5$ (4.2)
$\displaystyle x_1-x_2-x_3$ $\textstyle =$ $\displaystyle -1$ (4.3)

In matrix notation, we can rewrite the problem as $\mathbb{A}\vec x=\vec y$ as follows.

\begin{displaymath}\left[\begin{array}{rrr}
3&2&-1\\
-1&3&2\\
1&-1&-1 \en...
...left[
\begin{array}{r}
10 5 -1\\
\end{array}\right]
\end{displaymath}

The solution is made by taking the inverse of $\mathbb{A}$ to give

\begin{displaymath}\mathbb{A}^{-1}\mathbb{A}\vec x = \mathbb{A}^{-1}\vec y\rightarrow \vec
x=\mathbb{A}^{-1}\vec y \end{displaymath}

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 $\vec x = (-2,5,-6)$ which we can verify is the correct answer by trying $\mathbb{A}\vec x$ and seeing that it yields the original $\vec y$. Note that in this example we used the matrix multiplication operator * (not .*). This time it worked because the number of columns in $\mathbb{A}$ is equal to the number of rows in $\vec x$. An alternative way to solve the problem is to use the inverse of $A$ 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 $A$ 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 up previous contents
Next: 5. Data analysis Up: 4. Linear algebra Previous: 4.1 Basic operations   Contents
Gus Hart 2005-01-28