15.11.2014 Views

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

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

366 <strong>Chapter</strong> 4 <strong>Programm<strong>in</strong>g</strong> <strong>in</strong> <strong>Matlab</strong><br />

subrout<strong>in</strong>e is free to make changes to <strong>the</strong> value <strong>of</strong> <strong>the</strong> variable <strong>in</strong> that particular<br />

memory location.<br />

On <strong>the</strong> o<strong>the</strong>r hand, <strong>Matlab</strong> passes variables by value to function arguments.<br />

This means that <strong>the</strong> function that receives this value has no idea where <strong>the</strong> variable<br />

is actually located <strong>in</strong> memory and is unable to make changes to <strong>the</strong> variable<br />

<strong>in</strong> <strong>the</strong> caller’s workspace. In <strong>Matlab</strong>Speak, <strong>the</strong> variable that is passed to <strong>the</strong> function<br />

is local to <strong>the</strong> function, it exists <strong>in</strong> <strong>the</strong> function’s workspace. If <strong>the</strong> function<br />

makes an attempt to set or modify this variable, it does so to <strong>the</strong> variable <strong>in</strong> its<br />

workspace, not <strong>in</strong> <strong>the</strong> caller’s workspace.<br />

For eample, make <strong>the</strong> follow<strong>in</strong>g adjustments to <strong>the</strong> function localvar and save<br />

as localvar.m.<br />

function localvar(p)<br />

fpr<strong>in</strong>tf(’Function localvar received this value <strong>of</strong> p: %d\n’,p)<br />

p=12;<br />

fpr<strong>in</strong>tf(’Function localvar changed <strong>the</strong> value <strong>of</strong> p to: %d\n’,p)<br />

Exam<strong>in</strong>e <strong>the</strong> base workspace variable p. If needed, reset this variable with <strong>the</strong><br />

command p=24.<br />

>> p<br />

p =<br />

24<br />

Execute <strong>the</strong> function localvar by pass<strong>in</strong>g it <strong>the</strong> variable p from <strong>the</strong> base workspace.<br />

>> localvar(p)<br />

Function localvar received this value <strong>of</strong> p: 24<br />

Function localvar changed <strong>the</strong> value <strong>of</strong> p to: 12<br />

Now, exam<strong>in</strong>e <strong>the</strong> variable p <strong>in</strong> <strong>the</strong> base workspace.<br />

>> p<br />

p =<br />

24

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

Saved successfully!

Ooh no, something went wrong!