MATLAB Object-Oriented Programming

(Joyce) #1

Passing a nonhandle variable to a function does not affect the original variable that is in
the caller’s workspace. For example, myFunc modifies a local variable called var, but
when the function ends, the local variable var no longer exists:


function myFunc(var)
var = var + 1;
end


Define a variable and pass it to myfunc:


x = 12;
myFunc(x)


The value of x has not changed after executing myFunc(x):


disp(x)


12


The myFunc function can return the modified value, which you could assign to the same
variable name (x) or another variable.


function out = myFunc(var)
out = var + 1;
end


Modify a value in myfunc:


x = 12;
x = myFunc(x);
disp(x)


13


When the argument is a handle variable, the function copies only the handle, not the
object identified by that handle. Both handles (original and local copy) refer to the same
object.


When the function modifies the data referred to by the object handle, those changes are
accessible from the handle variable in the calling workspace without the need to return
the modified object.


For example, the modifySampleRate function changes the audioplayer sample rate:


Handle Object Behavior
Free download pdf