user466534
user466534

Reputation:

Global variable in matlab

let us consider following code which declares global variable in matlab function

function[y] = myfun2(x)
global b

a = 3;
y = x.^4.*sqrt(a*x+5)./(x.^2+b);
b = 4;

then following commands

global b;
>> b=1

b =

     1

>> y=myfun2(3)

returns me value

 y =

   30.3074

i have first question there why it is necessary to declare global variable second times?is it not enough to declare it inside function?and also my second question

following command

y=myfun2(3)

y =

   23.3134

does it means that second times it used number 4?how can i determine which b is used first time?i meant 1 or 4?thanks in advance

Upvotes: 2

Views: 1754

Answers (1)

Rishabh Goyal
Rishabh Goyal

Reputation: 99

@dato datuashvili,

You are confused with global variable.

Ordinarily, each MATLAB® function has its own local variables, which are separate from those of other functions, and from those of the base workspace. However, if several functions, and possibly the base workspace, all declare a particular name as global, they all share a single copy of that variable. Any assignment to that variable, in any function, is available to all the functions declaring it global. If the global variable does not exist the first time you issue the global statement, it is initialized to the empty matrix. If a variable with the same name as the global variable already exists in the current workspace, MATLAB issues a warning and changes the value of that variable to match the global.

Have a look on this page, which is also source of my answer.

http://www.mathworks.in/help/matlab/ref/global.html

In addition to that,

You need to declare x as a global variable in every scope (i.e. function/workspace) that you want it to be shared across. So, you need to write test1 as:

function test1()
  global x;
  x = 5;
end

The source to above answer is Declaring a global variable in MATLAB. If that does not help you, please notify me.

Upvotes: 1

Related Questions