Page 25 - MATLAB Recipes for Earth Sciences
P. 25
16 2 Introduction to MATLAB
The above display illustrates another important point about MATLAB.
Obviously the result of sum(A) are the four sums of the elements in the four
columns of A. The software prefers working with the columns of matrices. If you
wish to sum all elements of A and store the result in a scalar b, you simply type
b = sum(sum(A));
which first sums the colums of the matrix and then the elements of the re-
sulting vector. Now we have two variables A and b stored in the workspace.
We can easily check this by typing
whos
which is certainly the most frequently-used MATLAB command. The soft-
ware lists all variables contained in the workspace together with information
about their dimension, bytes and class.
Name Size Bytes Class
A 4x4 128 double array
ans 1x4 32 double array
b 1x1 8 double array
Grand total is 21 elements using 168 bytes
It is important to note that by default MATLAB is case sensitive, i.e., two
different variables A and a can be defi ned. In this context, it is recommended
to use capital letters for matrices and lower-case letters for vectors and sca-
lars. You could now delete the contents of the variable ans by typing
clear ans
Next we learn how specific matrix elements can be accessed or exchanged.
Typing
A(3,2)
simply returns the matrix element located in the third row and second col-
umn. The matrix indexing therefore follows the rule (row, column). We can
use this to access single or several matrix elements. As an example, we
type
A(3,2) = 30
to replace the element A(3,2) and displays the entire matrix
A =
2 4 3 7
9 3 -1 2
1 30 3 7
6 6 3 -2