tags:

views:

50

answers:

2

I have a variable in the MATLAB workspace and I want to pass this variable to a function in my GUI.

How do I achieve this task?

+1  A: 

You can use SETAPPDATA (in the main workpsace) and GETAPPDATA (in GUI) functions.

If you variable is someMatrix

setappdata(0,'someMatrix',someMatrix) % in the main workspace

someMatrix = getappdata(0,'someMatrix') % in GUI
yuk
+2  A: 

You can use the function EVALIN in your GUI to get the value of a variable from the base workspace. The following example extracts the value of the variable A in the base workspace and places that value in the local variable B:

B = evalin('base','A');

You could, for example, have an editable text box in your GUI that allows the user to enter the name of a variable to import from the base workspace. One of your GUI functions could then read the string from the editable text box and attempt to fetch that variable from the base workspace to use in some computation:

varName = get(hEditText,'String');    %# Get the string value from the uicontrol
                                      %#   object with handle hEditText
try                                   %# Make an attempt to...
  varValue = evalin('base',varName);  %#   get the value from the base workspace
catch exception                       %# Catch the exception if the above fails
  error(['Variable ''' varName ...    %# Throw an error
         ''' doesn''t exist in workspace.']);
end
gnovice
Using the base workspace as 'variable container', kind of 'global' variable storage, can be tempting. But removes all advantages of variable scoping! Every piece of code may change a variable in base workspace. This programming style makes errors really hard to track.
zellus
@zellus: I agree that there are much better ways to handle variables in a GUI, like using nested callback functions to maintain the values of local variables. However, the OP is specifically asking how to get a workspace variable into a GUI, and this is one of the ways.
gnovice
@gnovice: Your right, my comment belongs to the question and not to your answer.
zellus