MATLAB 2

One powerful capability in MATLAB is the way that you can manipulate and view matrices. This includes doing matrix math (addition, multiplication, etc.), and how we can view the data that is in a matrix. We have seen a taste of matrix manipulation in our experience with Python indexing for lists and strings, and MATLAB has similar capabilities. This lab will focus on a number of things in using matrix operations, including use of the colon (:) operator in MATLAB, which is one of its most powerful, yet often tricky, elements.

This set of notes can only start to describe all the things you can do with MATLAB. I have included a document “mtt.pdf” (“MATLAB Tips and Tricks”) that a group of MATLAB users on the internet put together a number of years ago describing various techniques to manipulate matrices and arrays in MATLAB in the fastest and most efficient way. Feel free to refer to it if you like for your personal knowledge as you use MATLAB in your research, but you won’t need to know all of the information contained therein for this class.

Matrix Math

MATLAB can perform complicated math on matrices with a succinct syntax (so that you do not need to include for loops to iterate over an entire matrix to do the same calculation on all of its elements. Doing math in this array fashion in MATLAB is generally more efficient than writing your own for loops, though this difference is much less than it used to be due to MATLAB’s “compiler.” However, the compiler does not work on MATLAB functions, so this remains an important skill when dealing with complex data analysis tasks. This efficiency comes at a cost to transparency: often, the syntax for such array operations can be rather opaque when compared to an explicit loop, and it may be tricky to (a) figure out how to express some desired computation as array math, and (b) decipher what someone else’s code is doing, particularly when that someone else is you and you wrote your code 2 months ago and cannot remember how it works. This highlights that you should always comment your code, and that commenting becomes especially important the more fancy your MATLAB skills become. If you hand in a homework assignment with complicated array operations that are not described with comments, you will lose points. We will discuss tips for writing MATLAB code this way in the next few labs.

Examples of ways to do array operations include, but are not limited to:

  • Matrix math, such as addition, subtraction, multiplication/division by a constant, can be done directly on matrices.

  • MATLAB is designed to do linear algebra, so it is often most efficient to write your operations as a series of matrix operations. You can use matrix multiplication and exponentiation on matrices, though the dimensions of the matrix must follow the rules for the corresponding operation.

  • If your operation is not true matrix multiplication, but rather array multiplication, division, or exponentiation (i.e. perform the given operation element by element), use .*, ./, or .^ on two matrices with identical dimensions. For example, if A and B are each 2x2 matrices, then the following loop calculations

    for ii=1:2
        for jj=1:2
            C(ii,jj) = A(ii,jj)*B(ii,jj)
        end
    end
    

    can be done concisely using C = A.*B. This is very handy, and I find myself using this operation much more frequently than true matrix multiplication.

  • Most built-in mathematical functions work on arrays without any need to do loops. Things like taking an exponential (exp( )), logarithm (log( )), trigonometric functions of all types (sin( ), cos( ), etc.)

Slicing, Viewing, and Broadcasting

The colon operator is very useful for looking at array slices (i.e. a particular range of a matrix) and viewing those particular contents. You can use it to refer to an entire range of an index, a particular range of an index, a particular spacing of an index (a nice and quick way to de-sample data). For example:

  • A(:,1) shows the first column of A
  • A(1,:) shows the first row of A
  • A(1:2,1) shows the first two elements of the first column of A
  • A(2:5,1) shows elements 2 through 5 of the first column of A
  • A(5:end,1) shows all elements beyond position 5 in the first column of A
  • A(1:2:7,1) shows the odd elements through 7 of the first column of A
  • A(2:2:end,2:2:end) shows only the even-numbered elements of A

As you can see, you can pull many tricks using the colon operator. Practice using it on a matrix to get more comfortable with it. You can use such tricks to broadcast only a particular range of data to another function. Note that there are a few differences from Python: the step (when provided) goes in the middle of the colons, and you use end to represent the last entry. Negative indices are not allowed in MATLAB.

Evaluating a Matrix with a Matrix

Another powerful (and often opaque) trick is to use a matrix to evaluate a matrix. The matrix must have all positive values within the limits of the matrix being evaluated, or be a logical matrix (see the next section). For example, if A is a 5x5 matrix, and b = [1 2 5] then

  • A(b,1) shows elements 1, 2, and 5 of the first column of A
  • A(2,b) shows elements 1, 2, and 5 of the second row of A
  • A(b,b) is a 3x3 matrix populated by the elements indexed by all possible pairs involving 1, 2, and 5

This is very handy trick for picking out certain pieces of a large dataset.

Logical Matrices

MATLAB also has a logical data type, which can have two values: 1 (true) and 0 (false). You can also create matrices of logicals. These are useful if you would like to find certain values of a matrix that satisfy particular conditions. Evaluating a matrix with a logical matrix requires that the logical matrix have the same length as the corresponding dimensionIn the following, A and B are vectors of the same length:

  • A > 1 returns a logical vector, where entry k is 1 if A(k) > 1 and 0 if A(k) <= 1
  • A > B returns a logical vector, where entry k is 1 if A(k) > B(k) and 0 if A(k) <= B(k)
  • A(A > 1) returns a vector containing only the entries of A that are greater than 1

The final type of expression above is extremely useful if you need to find data that exceeds a certain threshhold. See the exercises for an example application.

Exercises

  1. These problems use the datafile “newmadrid2015.txt” which is the earthquake catalog for the New Madrid Seismic Zone for 2015. The catalog is in ASCII format. Each line consists of four numbers: date (in decimal years), latitude, longitude, and magnitude. Read the data into MATLAB, saving the data as a large matrix.
  2. Use the colon operator to display all four pieces of data for the first event.
  3. Use the colon operator to display only the first 5 event dates in the command window. Then, use the colon operator to display the final 5 event magnitudes.
  4. Use the colon operator on the large matrix to view all four pieces of data for every 5th entry (i.e. entries 5, 10, 15, ...).
  5. Evaluate the large data matrix with another matrix to display all four pieces of information for events 20, 38, 98, 119, and 160.
  6. Using a logical matrix, display the date of all events with a magnitude above 3.0.
  7. Using a logical matrix, display the date of all events with a latitude smaller than \({36^\circ}\).
  8. Using a logical matrix, display the date and magnitude of all events in the rectangular region with latitudes between \({35.5^\circ}\) and \({36^\circ}\) and longitude between \({-90.5^\circ}\) and \({-90^\circ}\).
  9. Using a logical matrix, display the date of all events in January. You will need to convert decimal years into the appropriate format – try to do this using array math.