get th name and check the existence of a variable in workspace from gui

2 views (last 30 days)
Brasco , D.
Brasco , D. on 10 Sep 2018
Edited: Stephen23 on 10 Sep 2018
Let say we have a gui that consists of two listboxes.
In listbox1 we have variable names listed programmatically. For instance the variable names in listbox1 are listed as
'name_1'
'name_2'
'name_3' ...
'name_N'
I want to check the existence of the variable that I pick (click) in listbox1 and print something in listbox2.
The printing part is easy but I couldn't manage the checking.
Step by step:
  1. Click a variable in listbox1,
  2. Get the name of variable,
  3. Check the existence of that variable in workspace,
  4. Set a resulting string in listbox2.
I used
listbox1_index = get(handles.listbox1,'Value');
listbox1_string_index = get(handles.listbox1,'String');
var_name = listbox1_string_index{listbox1_index};
ex=evalin('base','exist(....)');
but it didn't work.
Can any one help me ?
  1 Comment
Stephen23
Stephen23 on 10 Sep 2018
This is an inefficient code design:
  • magically accessing variables in another workspace is slow, complex, and buggy, regardless of the method used to do this.
  • magically accessing numbered variables is a sign that you are doing something wrong: accessing numbered variables is slow, complex, and buggy. If the numbers indicate a sequence then they would be much better encoded using much simpler and much more efficient indexing.
  • querying the state of the workspace using who, whos, exist, etc, is slow. The MATLAB documentation specifically recommends against doing this:
Read more here:
Better (in the sense simpler, neater, more efficient, less buggy, easier to debug) GUI design simply passes data to the GUI function when it is called, does all of the processing within the GUI, then returns whatever values are required.
This is exactly the same advice that you received several years ago:

Sign in to comment.

Answers (1)

KSSV
KSSV on 10 Sep 2018
A = rand ;
B = rand(2) ;
C = rand(3) ;
S = whos ;
if any(strcmp({S.name},'A'))
fprintf('The variable exists\n')
else
fprintf('The variable does not exists\n')
end

Community Treasure Hunt

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

Start Hunting!

Translated by