Math 485 (Sect 2) -- Mathematical Modeling

[ Tutorial page | Course home page ]

Section 3: programming

You can create your own functions in MATLAB.

We will write a function, called "stab_eq" (for "stable equilibrium"), which computes the eigenvalues of the jacobian associated with the stable equilibrium of the pendulum for given values of the dimensionless friction coefficient alpha.

To do so, go to the "File" menu and create a new M-file. Then:

function e=stab_eq(alpha)

  % Lines that begin with % are comments.  You can explain
  % what you're doing to yourself!

  J = [0 1; -1 -alpha];
  e = eig(J);
Then save the file as "stab_eq.m", and we're done. We can now run the program to compute eigenvalues:

>> stab_eq(0)

ans =

        0 + 1.0000i
        0 - 1.0000i

>> stab_eq(1)

ans =

  -0.5000 + 0.8660i
  -0.5000 - 0.8660i

>> stab_eq(2)

ans =

    -1
    -1

>> stab_eq(3)

ans =

   -0.3820
   -2.6180
First line tells MATLAB that the function is named "stab_eq", and that the variable "e" will hold the result of the function. The only input argument is "alpha", but MATLAB functions can take as many arguments as you'd like. The rest is straightforward.

Let's now write a second function that uses "stab_eq" to do something interesting:

function plot_eigs(a0, a1, n)

  figure;      % make a new figure window
  hold on;     % do not erase figure between calls to plot()

  delta = (a1-a0)/n;

  for a = a0:delta:a1,
      e=stab_eq(a);
      plot(real(e),imag(e),'o');
  end
We can try it:
>> plot_eigs(0,4,100)
This plots the eigenvalues for the jacobian of the stable pendulum equilibrium, using 100 sample points between alpha=0 and alpha=4.

In the example above, the "for" statement begins a loop: MATLAB will evaluate the statements between "for" and "end" repeatedly, first with a=a0, then with a=a0+delta, then a=a0+2*delta, and so on, and stop when a > a1.

Last updated on February 4, 2008 by Kevin K. Lin