23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

3 Basic Program Components<br />

Note If you run a script that alters a variable that already exists in the<br />

caller’s workspace, that variable is overwritten by the script.<br />

Global Variables<br />

If several functions, and possibly the base workspace, all declare a particular<br />

name as global, then they all share a single copy of that variable. Any<br />

assignment to that variable, in any function, is available to all the other<br />

functions declaring it global.<br />

Suppose, for example, you want to study the effect of the interaction<br />

coefficients, α and β, in the Lotka-Volterra predator-prey model.<br />

Create an M-file, lotka.m.<br />

function yp = lotka(t,y)<br />

%LOTKA Lotka-Volterra predator-prey model.<br />

global ALPHA BETA<br />

yp = [y(1) - ALPHA*y(1)*y(2); -y(2) + BETA*y(1)*y(2)];<br />

Then interactively enter the statements<br />

global ALPHA BETA<br />

ALPHA = 0.01<br />

BETA = 0.02<br />

[t,y] = ode23(@lotka,[0,10],[1; 1]);<br />

plot(t,y)<br />

The two global statements make the values assigned to ALPHA and BETA at<br />

the command prompt available inside the function defined by lotka.m. They<br />

can be modified interactively and new solutions obtained without editing<br />

any files.<br />

3-4

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!