GUI pop-up menu in MATLAB

Chethan picture Chethan · Mar 26, 2013 · Viewed 19.7k times · Source

I've a pop-up menu with 5,10,15,20 the contents in that menu. using switch I've created this

val=get(hobject,'value');
switch val
    case '5'
        n=5;
    case '10'
        n=10;
    case '15'
        n=15;
    case '20'
        n=20;
end
guidata(hObject, handles);

where it represents number of output images. On pressing search button in the same GUI window it calls another function where i need to use this 'n'.

for i = 1:n          % Store top n matches...
    tempstr = char(resultNames(index(i)));
    fprintf(fid, '%s\r', tempstr);
    disp(resultNames(index(i)));
    disp(sortedValues(i));
    disp('  ')
end

How can i pass this 'n' to that code or function? any proper answer is appreciable.

Answer

wakjah picture wakjah · Mar 26, 2013

Well, to start with your switch statement is incorrect and unnecessary. The Value property of a dropdown is not the text contained in the current selection, it is the index of the current selection in its list. To get the string value of the list item currently selected, you would do:

contents = cellstr(get(hObject,'String')) % returns contents as cell array
contents{get(hObject,'Value')} % returns value of selected item from dropdown

That is, of course, assuming hObject is a handle that points to your dropdown box - which it will be only if you're in a callback that was raised by the dropdown itself. Further to that, note that there is no need to convert the string value via a discretised switch statement; you can just use the str2num or str2double functions.

Finally, if you need to access the value of the dropdown from outside one of its own callbacks, you need to use the handles structure that is passed into every callback (or that, in your sample, is returned from guidata). There will be a field in handles with the same name as your dropdown - this will be the handle via which you can access its properties.