MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1
If you use global variables, declare them using the global keyword before you access
them within any particular location (function or command line). For example, create a
function in a file called falling.m:

function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;

Then, enter these commands at the prompt:

global GRAVITY
GRAVITY = 32;
y = falling((0:.1:5)');

The two global statements make the value assigned to GRAVITY at the command prompt
available inside the function. However, as a more robust alternative, redefine the function
to accept the value as an input:

function h = falling(t,gravity)
h = 1/2*gravity*t.^2;

Then, enter these commands at the prompt:

GRAVITY = 32;
y = falling((0:.1:5)',GRAVITY);

Evaluating in Another Workspace


The evalin and assignin functions allow you to evaluate commands or variable names
from character vectors and specify whether to use the current or base workspace.

Like global variables, these functions carry risks of overwriting existing data. Use them
sparingly.

evalin and assignin are sometimes useful for callback functions in graphical user
interfaces to evaluate against the base workspace. For example, create a list box of
variable names from the base workspace:

function listBox
figure
lb = uicontrol('Style','listbox','Position',[10 10 100 100],...
'Callback',@update_listBox);
update_listBox(lb)

20 Function Basics

Free download pdf