Global variable not working in the MATLAB workspace

41 次查看(过去 30 天)
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

回答(2 个)

Image Analyst
Image Analyst 2017-11-26
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 2017-11-26
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.

类别

Help CenterFile Exchange 中查找有关 Variables 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by