Create contents of popup menu dynamically
    4 次查看(过去 30 天)
  
       显示 更早的评论
    
 I want to create a popup menu with contents dynamically,based on value of a variable n in my code.
 Example:- If n is 2,the contents should be Data1,Data2.
           If n is 3,the contents should be Data1,Data2,Data3.  
           ...................................................
           If n is x,the contents should be Data1,Data2,......Datax
2 个评论
  Jan
      
      
 2012-7-4
				Ok. What have you tried so far and what problems occurred? Did you read "doc uicontrol" already?
采纳的回答
  Mark Whirdy
      
 2012-7-4
        Hi Luffy
Not 100% sure I understand the degree of dynamism you're going for but stick the code below underneath whereever n changes (assuming handles is in scope there). Here you specify the menu contents cell array explicity in each case - does this fit your use-case?
switch n case 1 set(handles.popupmenu1,'String',{'Data1';'Data2'},'Value',1); case 2 set(handles.popupmenu1,'String',{'Data1';'Data2';'Data3'},'Value',1); end
Alternatively, if for some reason you're defining the contents to be a cellaray of 'Data#' whose length = n, then the code below should do it
n = 4; myarray = strcat('Data',cellfun(@num2str,num2cell((1:n)'),'UniformOutput',false)) set(handles.popupmenu1,'String',myarray,'Value',1);
All the best Mark
2 个评论
更多回答(1 个)
  Jan
      
      
 2012-7-5
        String  = sprintf('Data%d#', 1:n);
String(end) = [];
CString = regexp(String, '#', 'split');
uicontrol('Style', 'popupmenu', ...
          'String', String, ...
          'Units', 'pixels', ...
          'Position', [370, 60, 95, 21]);
3 个评论
  Samuel Hirsbrunner
 2016-7-23
				finde this on my researches... I may shorten the code again:
 String = sprintf('Data%d\n',1:size(Data))
by adding "\n" it made a new line on each value. so no need for the regesp() at least i think this works...
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!





