Understanding Scope: The Life Span of a Variable
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.
make a function my_fun and save this as my_fun.m
Now call this function from command line or script file
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
Now on command line, write
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