Asked by Igor
on 31 Mar 2011

MATLAB Help describes this topic (word "global") very shortly.

I ask it from such question:

M-file as function:

function [y]=y(x) a=2; y=a*x.^2 end

how to force the procedure to modify global variables? that is, after proc. work, some results will be saved in globals and be available for other procedures.

For example, assigning a=2 I wish to keep. But I don't want use simple ways: 1) text file 2) write [y,a] in header, or y=[y; a] in body

If I write global a; a=2

this haven't effect...

and may anybody give good practical code example with and without GLOBAL?

Answer by Jan
on 31 Mar 2011

Accepted Answer

Working with GLOBALs is fragile in all programming languages: It is very hard to find out, where and why the value was set the last time.

Therefore I'd use Paulo's approach ever: "function [y,a]=y(x)" and forward of [a] to all functions, which need it.

Another approach is using a dedicated function to store the value persistently:

function a = Store(Command, a)

persistent a_

switch Command

case 'get', a = a_;

case 'set', a_ = a;

otherwise error('unknown command');

end

Although this has the same drawback as GLOBAL ([a] can be influenced from anywhere), you can at least use the debugger to track changes and usage of [a].

But it is at least possible to use GLOBALs (I avoid using "y" as variable and function name at the same time):

function yValue = y(x)

global a

a = 2;

yValue = a * x .^ 2;

end

Then from the command line or inside another function:

global a

disp(a) % >> nothing

k = y(1:10);

disp(a) % >> 2

David Young
on 1 Apr 2011

Jan
on 1 Apr 2011

Igor
on 1 Apr 2011

i suppose that at restricted sphere it's a plus!

but GLOBAL var. must be unique named

it's needed more believe in programmer!?

Sign in to comment.

Answer by Paulo Silva
on 31 Mar 2011

The way you should always work with is:

function [y,a]=y(x)

if you still want to use global variables you must declare the variable as global everywhere you want to use it (other functions and workspace)

Jan
on 31 Mar 2011

@Paulo: Let me cite Matt Fig: "... the rest is just fluff".

Igor might be 8 or 88 years old, working with Matlab since 6 hours only, very tired or confused by the the impressive power of Matlab. Anyway, I do not see a reason to be inpolite.

Paulo Silva
on 31 Mar 2011

Paulo==BeingImpolite

ans =

1

Igor
on 1 Apr 2011

jokers...

MATLAB is a powerful THING!

Sign in to comment.

Answer by Walter Roberson
on 31 Mar 2011

Answer by David Young
on 31 Mar 2011

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.