- globals... a major cause of beginners writing slow, buggy, impossible-to-read code. Globals are the least recommended way of passing data between workspaces.
- dynamic variable names... a major cause of beginners writing slow, buggy, impossible-to-read code. MATLAB has a whole page advising to avoid string evaluation and creating variable names.
Automatically define (global) variables
7 次查看(过去 30 天)
显示 更早的评论
I would like to define several global variables (P1,P2,P3,...,Pn), where n is a number to be defined. I my first attempt was the following one:
for i = 1:n
global strcat('P',num2str(i))
end
This does not work, what is the proper way to do this?
1 个评论
Stephen23
2016-4-29
编辑:Stephen23
2016-4-29
"what is the proper way to do this?"
The proper way is: DON'T,
This is such a bad idea on so many levels:
So lets combine the two worst code practices into one big mess of impossible-to-debug code, and win some obfuscated code prizes while we are at it.
Hanging a hurricane lamp out on the verandah is a great idea if you want to attract all of the bugs in the neighborhood. If you want to keep your verandah clean and tidy, do not use globals and dynamically defined variable names.
Search this forum to know more about these topics.
采纳的回答
更多回答(3 个)
Image Analyst
2016-4-29
In each function where you want to access those numbers, define a single global variable P
global P;
Then, later when you've discovered how many P you want, in any of the functions where you have declared P as global, do this
P = zeros(1,n);
Of course you could declare an array of cells, structures, integers, doubles, or whatever you need - just use the proper initialization function.
It's extremely bad practice to poof into existence an unknown-in-advance number of variables with different names. I mean, how would you refer to them? What if later you said newVar = P39, but there turned out to be no P39? It's much better handled with an array where you merely use an index, and the index can easily be compared to the length of the array to make sure you don't go past the end of the array.
0 个评论
Kevin
2016-4-29
If you really need to use global variable, then I would suggest using structure. Create global structure that stores all your global variables.
function foo
global S
S.x1 = [1 2 3];
S.A1 = [1 3 4; 3 6 8];
end
0 个评论
Ben
2016-4-30
1 个评论
Image Analyst
2016-4-30
A structure array is simpler than a cell array and uses less overhead. Plus you don't have to worry about when to use parentheses, braces, or brackets. It's just a lot easier.
Like in a loop where you're calling imrect(), or whatever...
for k = 1 : 10
hRect = imrect(); % The function returns h, a handle to an imrect object.
P(k) = hRect;
end
Now P is a structure array where each element of P is a single structure, which is an ROI object.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!