Matlab accessing global variable from another m file?

조회 수: 19 (최근 30일)
will99
will99 2015년 10월 7일
댓글: Star Strider 2015년 10월 7일
so let say I have two files fileA.m & fileB.m in fileA.m I have this code
function fileA()
global dataX;
dataX = 100;
end
in fileB.m I want to use if to check the value this is what I have in fileB.m
function fileB()
if dataX == 100
fprintf('Value is %f \n' , dataX);
else
fprintf('Value is NOT %f \n' , dataX);
end
end
however I'm having problem every time I run fileB.m I get this error Undefined function or variable 'dataX'.
so how can I access global variable from another .m file .. I'm new to Matlab

채택된 답변

Star Strider
Star Strider 2015년 10월 7일
Please do not use global variables!
However if you must, you have to declare them as globals in every workspace that uses them. They don’t just magickally appear!
function fileB()
global dataX
if dataX == 100
fprintf('Value is %f \n' , dataX);
else
fprintf('Value is NOT %f \n' , dataX);
end
end
  댓글 수: 2
will99
will99 2015년 10월 7일
so I need to declare the variable in both fileB & fileA oh I thought it will be similar to java thank you :)
Star Strider
Star Strider 2015년 10월 7일
My pleasure.
MATLAB has its own rules about such things as globals. It is still best to pass ‘dataX’ and anything else your function needs as an argument rather than a global.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by