## Thursday, 17 March 2011

### Understanding Scope: The Life Span of a Variable

Scopes:
All the variable in any language have a span of life which is called their scope. Fortunately all variables created in MATLAB by a script or command line are alive until you delete them by calling clear or you shutdown matlab. While all the variable in the function become alive when that function is called and they are cleared automatically as soon as function call is ver.
if you call the function again, these variables are created again and they have lost their previous value.
try this:
make a function my_fun and save this as my_fun.m
function f=my_fun(x)
y=2*x;
f=log(y);
Now call this function from command line or script file
g=3;
h=my_fun(g);
Now type
whos
to see the variables created and you would see only g and h , no y.x or f variables are there.

Suppose you want that a variable created inside a function should not get deleted

How to make these variables' scope large:
there are two ways. One of the way is by declaring the variable global. Let us apply this above. In function definition, modify it as

function f=my_fun(x)
global y;
y=2*x;
f=log(y);
Now on command line, write
g=3;
h=my_fun(g);
global y;
Now type
whos
to see the variables. You can now see the variable y with value 6.
Remember you need to declare the variable global every place you want to use it. If you dont do this, then it is just a local variable unlinked from the global one even when their name are same

#### 7 comments:

1. Hi Guptaji,
I have a specific problem to be solved using neural network. I'll be more than happy, if you can post a MATLAB titorial (any video or guided tutorial).
The problem is I have a dependent output, say X. This is a function of independent variables, a, b, c. How to get a NN model for this, for optimization studies?

Thanks bhai.

2. OK , I will try to write this on this as soon as possible

3. See this blog for your problem.

http://matlabbyexamples.blogspot.com/2011/03/starting-with-neural-network-in-matlab.html

4. Great post! I see the great contents and step by step read really nice information.I gather this concept and more information. It's helpful for me my friend. Also great blog here with all of the valuable information you have.
Python Online Training
Learn Python Online

5. This comment has been removed by the author.

6. This comment has been removed by the author.

7. This comment has been removed by the author.