Brian
Brian

Reputation: 27392

Access Variables from within function using Globals

I want to access variables from within a function using globals

Global x y z
Answer = MyFunction(4)
y



Function Result = MyFunction(x)
y=x+1;
z=y+1;

I would like to be able to access the value of y from the last time I call the function. Is it possible to do this?

Upvotes: 2

Views: 3897

Answers (1)

zellus
zellus

Reputation: 9592

Create the following function on the MATLAB search path:

function z = myFunction(x)
global y
fprintf('in myFunction -> y = %f\n', y);
y=x+1;
z=y+1;
end

Call myFunction from a script or command line.

global y;
y = 0;
answer = myFunction(3);
fprintf('past myFunction -> answer = %f\n', answer);
fprintf('past myFunction -> y = %f\n', y);

Since handle classes have been introduced to the MATLAB object model, I suggest not using globals.

Upvotes: 3

Related Questions