Friday, October 17, 2008

Accessing Matrix Elements and some In-built Matrices


We ended the last discussion with a brief mention on how to construct higher-dimensional arrays using an in-built function/matrix called ones. It is one of the examples of the various in-built MATLAB functions/matrices. Although, we'll come to the discussion on how to use/exploit N-dimensional arrays in MATLAB when we discuss time varying covariances (volatility), now would be a good time to introduce some of those special matrices. 

In-built Matrices

1. ones: This generates a matrix which contains only '1's. Use help ones to see in which ways it can be used. 

2. zeros: As you would have guessed by now, this generates a matrix which contains only '0's. Again, use help zeros on how it works (not too different from ones).

3. eye: This generates an identity matrix (remember? - zeros everywhere except ones in the diagonal). 

You can use them to not only create other matrices, but also to allocate memory (more on this later). The fact that they are in-built, means creating matrices using them is a much faster way than any other way you can think of. 

Although this was touched upon in the first class, next we look at how to access individual elements from a matrix.

Accessing Elements of Matrices

Although this is trivial it is still important enough to be mentioned separately. If x is a matrix, the general expression to access an individual element is:

x(row index, column index)
% for a 2-D array

x(row index, column index, dimension)
% for a 3-D array

For example, say you define:

>> x = [1 2 3 ; 4 5 6; 7 8 9] ;

Then, x(1, 2) represents the element corresponding to the 1st row and 2nd column of the matrix x.

If you want to access an entire row of the matrix x:

x(row number, :)

Similarly, to access an entire column of the matrix x:

x(:, column number)

For example, 

>> x(2, :)

% gives:

ans =

     4     5     6

and

>> x(:, 3)  

% gives:

ans =

     3
     6
     9

and so on and so forth. So what the colon operator ' : ' does is access all elements in a particular dimension. 

This brings us to the second assignment question:

Assignment 1, Q2:  Define a big enough matrix (of size 5 X 5 or more) by using at least one or more of the functions ones, eye and zeros. Let's call it x. What is the output of of x(:, :) , x([1 2], :) and x([3 4], [5 6]) ? What is the logic in the way x([3 4], [5 6]) works ? Create another matrix of the same size as x (but different from x). Let's call it y. Multiply x and y in both possible ways. Can you do both x ^ y and x .^ y (and vice-versa) ? What if x and y were of different dimensions ?

Next we will take a more detailed look at operator precedence and some important linear algebra functions.