Global variable not working in the MATLAB workspace

40 views (last 30 days)
I wrote the function:
function seed(new_seed)
global ISEED
new_seed = round(new_seed);
ISEED = abs(new_seed);
I am using the value of ISEED in another function. But the function gives me the error:
Undefined function or variable 'ISEED'.
Is this a bug or did I make am mistake somewhere? I am using MATLAB R2017b

Answers (2)

Image Analyst
Image Analyst on 26 Nov 2017
The other function must also declare ISEED global otherwise it can't see it. Evidently you just tried to use it without declaring it. Even once it's past that, it must have a value assigned to it or else it will just be empty/null (which might be okay with you but just be aware of it).

KL
KL on 26 Nov 2017
why do you want to use Global variables in the first place?
...I have never seen MATLAB code where globals were the right thing to do...
read these links:
if you want to share ISEED variable between two or more workspaces, why not just pass it as parameter?
function ISEED = calculateISEED(new_seed)
...
end
and then in the other,
ISEED = calculateISEED(new_seed);
function output = someFunction(var1, var2, ISEED);
or use the function return directly,
function output = someFunction(var1, var2, calculateISEED(new_seed))
Explain what you are trying to do by using global and maybe we can suggest sensible alternatives.

Categories

Find more on Variables in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!