How to pass variable to a function created through the guide

自闭症网瘾萝莉.ら 提交于 2019-12-12 21:33:06

问题


I have developed a GUI in MATLAB GUIDE. What is the best way to make data from an external function or class available to functions created by GUIDE?


回答1:


The links supplied by ymihere look very helpful. In addition, some of the options (nested functions and using GUIDATA) discussed at those links are addressed in another post on SO: How to create a GUI inside a function in MATLAB? There are a couple of examples there of how the code looks for each case.

I am personally partial to using nested functions, as I feel like it creates shorter, cleaner code in most cases. However, it's probably the more difficult of the methods for sharing application data if you are a newer MATLAB user (it can take a little getting used to). The easiest option for you may be to set the 'UserData' property on your call to your function (as suggested by ymihere). If you saved your GUIDE GUI to "myGUI.m", then you would call:

>> hGUI = myGUI('UserData','hello');

where hGUI is a handle to your GUI object. You can then get the 'UserData' property to see that it contains the string 'hello':

>> get(hGUI,'UserData')

ans =

hello

Instead of 'hello', you can put anything you want, like a structure of data. You should be able to access the 'UserData' field of the figure from within the callbacks of your GUIDE m-file. You will have to get the figure handle from the handles argument passed to your callbacks.

EDIT: One drawback to using the 'UserData' property, or some of the other methods which attach data to an object, is that the data could be accidentally (or intentionally) overwritten or otherwise corrupted by the user or other applications. The benefit of using nested functions to share data between your GUI callbacks is that it insulates your code from anything the user or another application might do. Conversely, using global variables can be rather dangerous.




回答2:


I have no idea what you want to do exactly, but you may probably want to use the figure's UserData property:

Passing somevar when opening the form myfig:

h = myfig('UserData', somevar);

or later:

h = myfig();
[...]
set(h, 'UserData', somevar);

In the figure you can access the property with:

function some_Callback(hObject, eventdata, handles)
    somevar = get(hObject, 'UserData');

See link text and link text



来源:https://stackoverflow.com/questions/704391/how-to-pass-variable-to-a-function-created-through-the-guide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!