Physics 217, Matlab hints

Revised 2005-Nov-18

Full documentation is available from the "Help" button in MATLAB itself, or from the Mathworks website.

Please tell the Professor if you have suggestions for improvements to this documentation.

  1. Using software other than MATLAB.

    Some of the homework exercises involve general problem-solving than can be done equally well using other software such as Octave, Mathematica, Maple, etc. In these cases you are free to use other software. By doing so you miss out on the gradual build-up of MATLAB knowledge as we use it to solve harder and harder problems.

    Some of the homework exercises involve downloading and running MATLB scripts. For these you have to use MATLAB, or translate the script yourself for the software you are using.
  2. Running MATLAB

    On the artsci computers, you can find Matlab in the applications menu that is accessed by clicking on the "start" button.

    On Linux machines you can simply type matlab at a command prompt; you may first have to start the license server by typing /usr/local/matlab/etc/lmstart.
  3. Downloading and running MATLAB script files.

    The crucial thing is to download MATLAB files to a directory that MATLAB knows about, so it will find the file. There are two procedures.
  4. Creating a MATLAB function.

    In MATLAB, each function must live in its own file, called an ``M-file''. To create a function, click on File->New->M-file to open the M-file editor. When you have typed in the function, click File->Save as to save it and give it a name, which must end in ".m". Then you can run the function at the MATLAB prompt by typing its name (without the ".m"). A simple example of an M-file is the "bump.m" function for a wavefunction localized near x=0:
    function psi = bump(x,a)
     C=1;
     psi = C .* 1./(1+(x./a).^2);
    return
    
    (Note that this version is not properly normalized.)
  5. Operators in MATLAB expressions

    In the bump.m function shown above, the mathematical expression is fairly easy to understand, except that the mathematical operators *, /, and ^ each have a dot "." in front of them. This is a MATLAB convention that ensures that when the function's argument is a vector of positions, eg
    bump([1.5, 2.0, 2.5], 2.5)
    
    it will return a vector of values of the function at those positions:
       0.3710  0.3077  0.2523
    
    Technically, you only need dots in front of ^ operators for which the first argument might be a vector, and * and / operators for which the quantities on each side of the operator could both be vectors. The MATLAB function quad gives a vector argument to the function it is integrating, so vectors may crop up when you don't expect them. The safest thing is to put a dot in front of every * /, and ^ operator in all your functions.

    If you forget the dots in front of operators you may get hard-to-understand error messages. If somewhere you have written a^b instead of a.^b, you may get
    ??? Error using ==> mpower
    Matrix must be square.
    
    If somewhere you have written a*b instead of a.*b, you may get
    ??? Error using ==> mtimes
    Inner matrix dimensions must agree.
    
    The hardest one to debug is if you have used / instead of ./ somewhere in a function. If you integrate the function, this may cause quad to give a very odd error message:
    ??? Attempted to access y(7); index out of bounds because numel(y)=1.
    
  6. Functions in MATLAB expressions

    If you need to take a square root, cosine, etc, MATLAB has builtin functions that do this in an obvious way. The constant Pi is also available.
    sqrt(2)*cos(2*pi)
    1.4142
    
  7. Plotting functions

    You can use the fplot function, which needs the function handle (its name with at "@" in front), and the x-limits over which to plot:
    fplot(@cos,[-pi,pi])
    
    To specify the y-limits of the plot as well as the x-limits, just include them in the limits vector:
    fplot(@sin, [-pi,pi,-2,2])
    
    You can also explicitly construct a list of values of x and values of the function at those points, and pass them to the plot function:
    xrange = -pi : 0.1 : pi
    plot(xrange,cos(xrange))
    
    (The first line makes a list of values of x from -pi to pi in steps of 0.1.)
  8. Anonymous functions (not available in older versions of MATLAB)

    In places where it expects a "function handle", you can give MATLAB a one-statement function definition right there on the spot. So instead of constructing a M-file for the "square" function
    function s = sqr(x)
    s = x.*x;
    return
    
    which could then be plotted with
    fplot(@sqr,[-2,2])
    
    you can just write
    fplot(@(x) x.*x ,[-2,2])
    
    where the expression @(x) x.*x is an unnamed ("anonymous") function definition for calculating the square of its argument. This is particularly useful if you want to use a multi-argument function. For example, suppose you have an M-file for the "pwr" function
    function s = pwr(x,n)
    s = x.^n;
    return
    
    You can plot various polynomials over the range x=-2 to +2 by typing
    fplot(@(x) pwr(x,2), [-2,2])
    fplot(@(x) pwr(x,3), [-2,2])
    fplot(@(x) pwr(x,2) - pwr(x,3)/2, [-2,2])
    
    To make a simultaneous plot of multiple functions, create an anonymous function that returns their values in an array. Eg:
    fplot(@(x) [sin(x),cos(x)],[0,2*pi,-2,2])
    
    N.B: If you have an older version of MATLAB that lacks anonymous functions, you can achieve the same result by passing a string that MATLAB can interpret as some function of x:
    fplot('pwr(x,2)', [-2,2])
    fplot('pwr(x,2)-pwr(x,3)/2', [-2,2])
    
  9. Integration in MATLAB

    If you have defined some function in an M-file, like the sqr function described above, then you can integrate it from -2 to 2, say, by typing
    quad(@sqr, -2, 2)
    
    (quad stands for "quadrature", an old term for integration). Again, you can use an anonymous function instead,
    quad(@(x) x.*x , -2, 2)
    
    Unfortunately, quad cannot deal with infinite limits of integration: you just have to make them very large but finite (see below).
  10. Complex numbers in MATLAB

    The square root of -1 is written is written as i or j in MATLAB expressions, and MATLAB writes it as i in output:
    >> exp(i*pi/4)
    ans =
       0.7071 + 0.7071i
    
    Note that older versions of MATLAB may only understand j, not i. You can obtain real and imaginary parts of any expression using the real and imag functions. MATLAB functions can accept complex arguments, so you can write things like
    quad( @(x) exp(3*j*x).*exp(-(x+1).^2),-10^6,10^6)
    
    and you get a complex answer.

    If you plot a complex function, MATLAB will take the real part and plot that, giving a warning message that it threw away imaginary parts.