how can I take a global variable declared in a program, take it in a function, change its value inside the fuction and give it again to the program as global?

Hi! I have the following Problem: I have a variable declared in my program, whose value I want to Change in a function and then return it to the program as global, so that when I call the function again the value stored in there is the one I calculated the last time within the function. If anyone could help me, please...

 Accepted Answer

You don't need to pass global variables anywhere.
You just keep putting
global myVariable
within any scope in which you wish to use it.
That said, it is terrible programming technique to use global variables. Just do something like:
value = doSomething( value );
in your main program with a normal (non-global) variable passed into a function and then passed out again after being updated. There are other techniques too, but that is probably the simplest.

3 Comments

Hi! I should probably explain better what I Need to do.
In my program I define as global two variables that have to be taken by a function. This variables define the Initial conditions for this function to create the following two variables that would define the next state and would be the initial conditions for the next call of the function. The Name of this variables should be the same. (the Name of the variables that the function is taken from the program when it is called should be the same as for the variables it creates, as this variables would define the Initial conditions for the next call)
I mean, in my program I define the two variables and give them the first values (Initial conditions for the first call of the function)
global Initial_condition_1 Initial_condition_1=10; global intiial_condition2 Initial_condition2=200;
%I call the function that Needs this values to produce the next two values and for it to take the variables, inside the function I write:
global intiial_condition2 global Initial_condition_1
%do Operation_1 and Operation_2 and assign them the correspondent names intiial_condition2=Operation_2 Initial_condition_1=Operation_1 Initial_condition_1 %end function and in the next call the function should be able to take this new values and not those defined at the program for its first call (10 and 200)
Thank you very much Adam, I´ve just achived what I wanted!
I don't think that changes anything I said though. The whole purpose of functions is that they take input arguments and can send back output arguments. You can pass out the same thing you pass in and then pass it in again next time you call the function if that is what you wish to do.

Sign in to comment.

More Answers (0)

Categories

Find more on Scope Variables and Generate Names in Help Center and File Exchange

Asked:

on 5 Mar 2015

Commented:

on 6 Mar 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!