Define multible Global Variables

Hello,
i used to declare global variables like this.
global p
% Körper 1
p.b1 = 1;
p.h1 = 0.6;
p.h1s = 0.3;
p.hp = 0.5;
...
This isn´t working anymore. does somebody know why?

답변 (1개)

Adam Danz
Adam Danz 2019년 5월 19일
편집: Adam Danz 2019년 5월 20일

2 개 추천

Your declarations should (still) work. Don't forget that you must declare the global variables again in the local workspace in order to access them.
global p
p.b1 = 1;
p.h1 = 0.6;
function dontUseGlobalVariables()
global p
% Now you have access to the p structure.
end
Or maybe a clear() command cleared your global variable between it's declaration and its retreival.
But again, please see this link to this comment to learn why global variables are a sign of bad programming.

댓글 수: 2

John D'Errico
John D'Errico 2019년 5월 19일
Good function name. :)
Rik
Rik 2019년 5월 19일
The only additional advice I would give is this: if you absolutely need to use globals, use a long name that contains the name of your top level function and is very descriptive. Using a long avoids collisions with other functions that might be using a similarly named variable. You have 63 characters for your variable name, you should use more than just 1.
I you think the name is too long and cumbersome to work with, create a temporary copy internal to your function. If you are not modifying the global there is no downside, thanks to the copy-on-write behavior of Matlab.

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

카테고리

도움말 센터File Exchange에서 Variables에 대해 자세히 알아보기

질문:

2019년 5월 19일

편집:

2019년 5월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by