MATLAB HINTS - HOMEWORK 2
M. Nelson  Spring 2004

New Matlab Commands

Review the commands from  Homework 0 and Homework 1.
ones
Ones array.
    ones(N) is an N-by-N matrix of ones (NOTE: not an N-by-1 vector)
    ones(M,N) or ones([M,N]) is an M-by-N matrix of ones.
    ones(M,N,P,...) or ones([M,N,P,...]) is an M-by-N-by-P-... array of ones.
    ones(size(A)) is an array of all ones, the same size as A.
zeros Zeros array.
    zeros(N) is an N-by-N matrix of zeros (NOTE: not an N-by-1 vector)
    zeros(M,N) or zeros([M,N]) is an M-by-N matrix of zeros.
    zeros(M,N,P,...) or ozeros([M,N,P,...]) is an M-by-N-by-P-... array of zeros.
    zeros(size(A)) is an array of all zeros, the same size as A.


New Matlab Techniques
Pre-allocating arrays
Matlab will let you create arrays on-the-fly without declaring them ahead-of-time. This is very  convenient feature when using small arrays, however there can be a sustantial performance penalty when the arrays get large.  Here's an explanation, from the mathworks.com website:

FOR loops can cause memory fragmentation problems because MATLAB does not know how big the final matrix array will be upon the conclusion of the FOR loop. For example, look at the following two FOR loops:

    %Example 1 - NOT RECOMMENDED
    clear
    for i=1:1000
    x(i)= sqrt(i);
    end
 
    %Example 2 - NOT RECOMMENDED
    clear
    x = [];
    for i=1:1000
    x = [x; sqrt(i)];
    end
The first time through the FOR loop, MATLAB requests enough memory from the operating system to create a 1 x 1 matrix, and creates x(1)=1. When i=2, MATLAB requests more memory so a 1 x 2 matrix can be stored. If this additional memory is in the same continuous memory strip as when x(1)=1, MATLAB will simply add the additional number in the same memory strip. If the original memory strip is only big enough for a 1x1 matrix, MATLAB moves the x(1)=1 and places it into a memory spot that is large enough for the 1x2 matrix. Since the matrix is now 1x2, the original memory slot is useless to MATLAB for any matrix larger than 1x1. This memory is now fragmented. You can probably see how this could cause big problems with large FOR loops.

This usually isns't a noticeable problem for small arrays (less than 1000 elements). But if you carry out large simulations, the for loop will become slower-and-slower as the simulation runs. The way to avoid the problem is to pre-allocate arrays before using them like this:


    %Example 3 - RECOMMENDED
    clear
    NSTEPS = 1000;
    x = zeros(NSTEPS, 1); % pre-allocate array
    for i=1:NSTEPS
        x(i)= sqrt(i);
    end

In this case, MATLAB allocates enough space for all 1000 elements of x and initializes them to zero with a single call to the function zeros. Now, MATLAB doesn't have to do any memory re-allocation during execution of the main loop.