Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
About global variable

Subject: About global variable

From: YIMING

Date: 10 Jan, 2011 17:25:05

Message: 1 of 3

Hey all,

Suppose I defined a variable x in file1.m, however I might wish to use this 'x' and modify its value in another file, say, file2.m and x in file1.m should understand its value will be changed outside.

CAN I ACHIEVE THIS?

Thanks in advance.

Subject: About global variable

From: Sean de

Date: 10 Jan, 2011 17:40:21

Message: 2 of 3

"YIMING" wrote in message <igffdh$d54$1@fred.mathworks.com>...
> Hey all,
>
> Suppose I defined a variable x in file1.m, however I might wish to use this 'x' and modify its value in another file, say, file2.m and x in file1.m should understand its value will be changed outside.
>
> CAN I ACHIEVE THIS?
>
> Thanks in advance.

Yes.

%Best way
doc function

%Other way
doc global

Subject: About global variable

From: David Young

Date: 10 Jan, 2011 17:45:08

Message: 3 of 3

You can achieve this - but unless you have a very special reason to need to do this, you should not attempt it as it leads to programs that are likely to have bugs, and which cannot easily be maintained.

A much better idea is to pass the value of x into the other function as an argument, and get back any computed value as a result. This is almost always all you need.

If you do need a more sophisticated way to transfer information, look at using Matlab's object-oriented structures. Then x can be an instance variable of a class, and methods of the class can all access it.

You may have heard of global variables. My strong advice is never to use them. If you think you need them, try reanalysing your problem first.

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us