teaLeef
teaLeef

Reputation: 1989

Global variables in matlab

I define a variable d like this

global d
d = 4;

However, when I later call this variable in a function, it is not recognized Undefined function or variable 'd'.

Isn't this the way global variables are declared?

Upvotes: 0

Views: 655

Answers (1)

herohuyongtao
herohuyongtao

Reputation: 50657

In your function that calls this global variable, you need to add the following line to the function before using it:

global d;

It is necessary declare a variable as global within a function body in order to access it. For example,

function testglobal()
clearvars -global
global d
f ()
d == 1

function f()
d = 1;

does not set the value of the global variable x to 1. In order to change the value of the global variable x, you must also declare it to be global within the function body, like this

function testglobal() 
clearvars -global
global d
f()
d == 1

function f()
global d;
d = 1;

Check out here for more info.

Upvotes: 3

Related Questions