MATLAB: How to create a list with all variables to let user choose those he wants for

inputlistdlgvars

Hi! I would like to take all the variables from the workspace starting with C (which are structs of data)
S = whos(C*)
And display them in a list to let the user choose some of them to be var1, var2… So the code would run with these var1, var2 depending the ones choosed from the user. Tried with listdlg
s= whos( 'C*');
str = {s.name};
[z,v] = listdlg('PromptString','Select variables',...
'SelectionMode','multiple',...
'ListString',str)
var1 = z(1);
var2 = z(2);...
But Z gives me only the position, not the variables choosed. If choose the 1st and 3rd, Z would be ( 1 3),instead of C… and C…(the variables choosed). Any idea in how to do it?
Thanks in advance.

Best Answer

Try to access variable names dynamically will be buggy any slow, and is not recommended. No matter how much beginners love inventing the idea, trying to access variables names like this will always make code be slow and impossible to debug:
A much simpler, faster, and easier way to code this would be to put all of the data into one structure. Then the task is trivial:
% Define a structure:
S.X = 'anna';
S.Y = 'bob';
S.Z = 'cath';
% Let the user pick some of the fields:
C = fieldnames(S);
idx = listdlg('PromptString','Select variables',...
'SelectionMode','multiple',...
'ListString',C);
% Show the values of the fields that the user picked:
for k = 1:numel(idx)
S.(C{idx(k)})
end