Pass String as Variable Into Function

22 次查看(过去 30 天)
Sorry, I posted a previous question that was convoluted and didn't really address my main concern. I'm trying to pass a string which is the variable name of a pre-existing UI object into the 'set' function inside a callback function. For example, set(variable1, ...), but I'm not sure how to convert the string 'variable1' into the literal word variable1 to be used in 'set'. Any help is appreciated! Thanks.
Edit: I'm not fond of using it, but I tried the eval function:
eval(['set(variable' num2str(1) ', "String", "hello")']) ;
Yet it doesn't work (I get the error "Invalid parameter/value pair arguments.")
Second Edit: I found the solution! Just use handles format instead:
eval(['variable' num2str(1) '.String = "hello"'])
  1 个评论
Mike Wilson
Mike Wilson 2020-9-21
Why bother giving such feedback when obviously you feel so much superior to those who know less than you. Get off your high horse and be nice to people.

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2017-12-21
Put your data into the handles structure and then use dynamic fieldnames
varname = sprintf('variable%d', 1);
set( handles.(varname), 'String', 'hello')
Or better yet,
variables = [handles.variable1, handles.variable2, handles.variable3, ....];
which_handle = variables(1);
set(which_handle, 'String', 'hello')
  5 个评论
Walter Roberson
Walter Roberson 2018-1-3
OpenFcn callback is not called automatically; it is a special name that GUIDE knows rather than being a true callback. CreateFcn callback always exist though.
However, you must have a section of your code that is initializing the GUI. You should construct the list of handles as you call uicontrol() or whatever to create the GUI.
variables(1) = uicontrol(...)
variables(2) = uicontrol(...)
and then just make sure you place the variables variable somewhere accessible. http://matlab.wikia.com/wiki/FAQ#How_can_I_share_data_between_callback_functions_in_my_GUI.28s.29.3F
Andrew
Andrew 2018-1-3
Ah ok I was able to initialize it that way. It works perfectly, thank you again.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Interactive Control and Callbacks 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by