2

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Persistent variables can also be a good alternative to a global, depending on what you are trying to do. I agree that the use of globals should be avoided whenever possible (which is most of the time),

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.