How use function variables?

1 次查看(过去 30 天)
Opera Era
Opera Era 2017-4-24
评论: Stephen23 2017-4-24
I have function with many variables,but they calculating depending on one var.I try to do GUI
function pushbutton1_Callback(hObject, eventdata, handles)
N=str2num(get(handles.edit4,'String'));
product(N);
and function
function [k,a,m,x,X,u,W,A,L]=product(N)
...
How can I use variables k,a,m,x,X,u,W,A,L?Read them?
  2 个评论
Opera Era
Opera Era 2017-4-24
I found solition.Just use global varuables like this:
function pushbutton1_Callback(hObject, eventdata, handles)
N=str2num(get(handles.edit4,'String'));
product(N);
global x;
x;
and
function product(N)
global x;x=(N+1);
Stephen23
Stephen23 2017-4-24
"I found solition. Just use global varuables like this"
You just found the second-worst way of passing data between workspaces. Do not use globals. Using global variables will make your code buggy and very hard to debug.
The documenation explains better methods of passing data (note the warnings about using globals):

请先登录,再进行评论。

回答(1 个)

Jan
Jan 2017-4-24
Using globals is a really bad idea. I will work at first, but as soon as the program grows, the problems will become worse and worse. Imagine that you open multiple instances of your GUI. Then you cannot predict reliably, when or who has causes the last change of the global variable. What happens, if another user runs your code and defines a global variable called "x" also?
This does not concern Matlab only, but using globals is a shot in the knee in any programming language.
Use either:
[k,a,m,x,X,u,W,A,L] = product(N);
This is clean and clear. Or if you think that these are too many variables to be clear for the user during reading the code, store them in a struct:
function ProductData = product(N)
ProductData.k = ...
ProductData.a = ...
... etc.
and
ProductData = product(N);
This is efficient, clean, clear and does not impede the debugging. You can run multiple instances of the code and it does not touch any other codes.

类别

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