Madhavi
Madhavi

Reputation:

How to pass variable to a function created through the guide

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?

Upvotes: 2

Views: 4756

Answers (2)

gnovice
gnovice

Reputation: 125854

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.

Upvotes: 3

ymihere
ymihere

Reputation: 381

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

Upvotes: 2

Related Questions