PROGRAMMING IN MATLAB

Matlab provides a friendly interactive environment for scientific programming and visualization. While Matlab is not intended as a substitute for programming languages like Fortran and C, it is very helpful for developing and testing of models, as well as, obtaining immediate feedback on directions for solving difficult problems.

In this section we will introduce many useful constructs used over and over again in Matlab programming.

EXERCISES

  1. Write a short Matlab program to input an integer n and build a n by n matrix with the numbers 1,2,... ,n on the main diagonal and zeros everywhere else (hint: Look at the command diag .
  2. Write a short Matlab program to input an integer n and build the n by n matrix A with entries a_{ij}=3^{i j}.
  3. Write a short Matlab program to compute the first 100 Fibonnaci numbers: a_1=1, a_2=1, a_n=a_{n-1}+a_{n-2}
  4. Write a Matlab m-file to Input an integer n, a number w and a vector with n components, x.
  5. n=input('n= ');
    w=input('w = ');
    x=input(' an n-vector, x = ')
    

    Step two: write a for loop program to build a matrix A with the given entries. Then, redo the problem the easy way using matlab syntax:

    1. a_{ij}=w^((i-1)(j-1)) Note this not matlab syntax
    2. b_{ij}=1/(i+j-1) Note this not matlab syntax
    3. c_{ij}=x_i^(j-1) Note this not matlab syntax


  6. Write a program to compute the binomial coefficients C(n,r). Do this by building a matrix P which is of size (n+1) by (n+1) for a given n so that p_{ij} satisfies
  7. p_{i,1}=p_{1,j}=1,
    for i+j <= (n+2), p_{i,j}=p_{i,(j-1)}+p_{(i-1),j},
    for i+j > (n+1), p_{i,j}=0
    

    You can use loops but it is much easier to use the built-in commands diag, pascal and rot90.

    % pascal(k) builds the pascal matrix of size k by k
    % rot90(A) rotates the matrix A by 90 degrees
    % diag(A) builds a column vector from the diagonal of A
  8. Write a program to carry out Euclids algorithm for computing the greatest common divisor of two numbers a and b. The algorithm is:
    1. input two numbers a and b
    2. compute the remainder of a/b
    3. replace a by b
    4. replace b by the remainder computed in 2)
    5. repeat the second through fourth steps until b is zero
    6. the gcd is the final value of a
  9. Redo the Lottery problem we did using Maple.


RETURN TO MAIN DOC