MATLAB Answers

Calling variables from a GUI into a script

14 ビュー (過去 30 日間)
Paige Moseley
Paige Moseley 2019 年 3 月 14 日
回答済み: Rik 2019 年 3 月 24 日
I have a GUI (using GUIDE) which asks the user for 8 different inputs. I have a script that will use this data to solve a couple of equations and plot some graphs. I want to run the GUI from the .m file and after the pushbutton is clicked, use the data from the GUI to run the script. My script keeps saying that the variables are undefined and will not run the script -- how to I save the GUI variables to have them run in the script? And does this need to be done in the script or the GUI, or both?

回答 (2 件)

Kevin Phung
Kevin Phung 2019 年 3 月 14 日
編集済み: Kevin Phung 2019 年 3 月 14 日
The variables are undefined because your graphic objects have lost their handles, because those handles are beyond the scope of your current process.
You should set the script to be the callback function for the pushbutton assign tags (Tag property of your graphic objects) to your graphic objects so that you can assign them a handle in your script.
for example if I had an edit field that I assigned the tag 'edit1' in GUIDE,
then in your callback function for your pushbutton I can retrieve its properties by:
found_edit = findobj(gcf,'Tag','edit1'); %in current figure, look for an object with tag 'edit1'
found_edit.String %this retrieves the string in the edit field.
I dont prefer using guide, so usually when I create my uicontrols I assign them a tag with:
edit1 = uicontrol('Style','edit','Tag','edit1')
then I can refer back to them in any function I want, so as long the figure and it exists.

Rik 2019 年 3 月 24 日
You shouldn't be using a script, but you should use a function instead. That way you have encapsulated the process. You can use the user input from the edit fields as the input to your function, so that it can do what it needs to do, without interfering with the variables you defined in your GUI code.
Although there is merrit to Kevin's suggestion, I would advice against it. I prefer not to make my function dependent on a particular GUI running. What I tend to do is to provide an optional parameter that specifies the target axes, so I can either use it to display output to a specific GUI axes, or use it without a GUI and let Matlab determine the target axes with gca.


Community Treasure Hunt

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

Start Hunting!

Translated by