How use function variables?

조회 수: 2 (최근 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