MATLAB Answers

Creating Variables with GUI inputs

58 views (last 30 days)
Erick Magana
Erick Magana on 13 Nov 2019
Commented: Erick Magana on 14 Nov 2019
I am trying to create a GUI with matlab and in order to make it work properly I need to ask for user input. I want to store these inputs in a variable and use them in the main part of my code. I have done some research but only found out that I could not create variables in a function and call them in an other fucntion. Is there anyway to do this? If so how would i incorperate it into my code?
Erick Magana
Erick Magana on 14 Nov 2019
Thanks, this all worked and gave me good insight on how Matlab works

Sign in to comment.

Answers (1)

Thomas Satterly
Thomas Satterly on 13 Nov 2019
There are a number of ways to store data in a GUI so that it's accessible to different functions. Matlab's suggested way of passing data around a GUI is by using the setappdata and getappdata functions. Ex:
fh = figure;
inputField = uicontrol('Style', 'edit', ...
'Units', 'normalized', 'Position', [0.1 0.1 0.2 0.1], ...
'Callback', @(src, event) inputNewValue(src, event, fh));
label = uicontrol('Style', 'text', 'String', '', ...
'Units', 'normalized', 'Position', [0.7 0.1 0.2 0.1], ...
'BackgroundColor', [0.9 0.9 0.9]);
button = uicontrol('Style', 'pushbutton', 'String', 'Copy Input', ...
'Units', 'normalized', 'Position', [0.4 0.1 0.2 0.1], ...
'Callback', @(src, event) buttonPressCallback(src, event, fh, label));
function inputNewValue(src, event, handle)
setappdata(handle, 'InputString', src.String);
function buttonPressCallback(src, event, handle, output)
data = getappdata(handle, 'InputString');
if isempty(data)
output.String = '(No Input)';
output.String = data;
setappdata and getappdata work on any graphics object, not just figures, so it's possible to have multiple graphics objects with the same functionality (like multiple tabs) that can each store their own data in the same manner, allowing for some nice code re-use. It's also a good practice to initialize all the app data you need, that way you won't be risking empty values being returned from getappdata
There are other methods for passing around data, as noted by Stephen's comment, that are worth investigating as they may be a better fit for your use case.

Community Treasure Hunt

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

Start Hunting!

Translated by