How use function variables?

1 view (last 30 days)
Opera Era
Opera Era on 24 Apr 2017
Commented: Stephen23 on 24 Apr 2017
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 Comments
Opera Era
Opera Era on 24 Apr 2017
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 on 24 Apr 2017
"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):

Sign in to comment.

Answers (1)

Jan
Jan on 24 Apr 2017
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.

Categories

Find more on Variables in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!