Chapter 4: Programming in Matlab - College of the Redwoods
Chapter 4: Programming in Matlab - College of the Redwoods
Chapter 4: Programming in Matlab - College of the Redwoods
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Section 4.4 Variable Scope <strong>in</strong> <strong>Matlab</strong> 363<br />
>> whos<br />
Name Size Bytes Class<br />
M 3x3 72 double array<br />
p 1x1 8 double array<br />
s 1x1 8 double array<br />
x 1x5 40 double array<br />
Note that <strong>the</strong> variables x, s, and p, created <strong>in</strong> <strong>the</strong> script, rema<strong>in</strong> present <strong>in</strong> <strong>the</strong><br />
base workspace when <strong>the</strong> script completes execution.<br />
If a variable exists <strong>in</strong> <strong>the</strong> base workspace, <strong>the</strong>n a script executed <strong>in</strong> <strong>the</strong> base<br />
workspace has access to that variable. As an example, enter <strong>the</strong> follow<strong>in</strong>g l<strong>in</strong>es <strong>in</strong><br />
<strong>the</strong> <strong>Matlab</strong> editor and save <strong>the</strong> script as usebase.m.<br />
fpr<strong>in</strong>tf(’Chang<strong>in</strong>g <strong>the</strong> base variable p.\n’)<br />
p=1000;<br />
fpr<strong>in</strong>tf(’The base variable p is now %d.\n’,p)<br />
Execute <strong>the</strong> script.<br />
>> usebase<br />
Chang<strong>in</strong>g <strong>the</strong> base variable p.<br />
The base variable p is now 1000.<br />
Now, at <strong>the</strong> <strong>Matlab</strong> prompt, exam<strong>in</strong>e <strong>the</strong> contents <strong>of</strong> <strong>the</strong> variable p <strong>in</strong> <strong>the</strong> base<br />
workspace.<br />
>> p<br />
p =<br />
1000<br />
Note that <strong>the</strong> script had both access to and <strong>the</strong> ability to change <strong>the</strong> base workspace<br />
variable p.