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.
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.
The way to pass information around a GUI is to use the the handles structure. If you created your GUI using GUIDE handles should have been created in the opening function. You can modify the opening function to add field and initial values to handles. For example, you could add the following to the opening function:
handles.n = 1; % This initializes handles.n to a default value in case the search button is
% pushed before an item in the menu is selected.
Then include the following in the call back for the menu to update and store the value of n:
handles.n = val; % This is updated every time an item from the menu is selected.
guidata(hObject,handles);
In the call back from the search button you can access the value of n and pass it to your other function like this:
n = handles.n;
myFunction(n);
Your other function will have start with something like this:
function [] = myFunction(n)
followed by the rest of the code you included above. You'll have to make sure myFunction.m is in the Matlab search path (can be set using addpath or by clicking the set path button in Matlab.)
Related
I have four items(Types of soils) to be inserted in popup menu and the output should be integer values(porosities) displayed using a static text. How this can be done?
I guess you will be using GUIDE to create your GUI. Here is a simple code for populating a popup menu with pre-defined strings and use the selected item to change the displayed output in the static text:
1) In order to populate the popup menu, simply create a cell array of strings and set the 'String' property of the menu to that cell array:
% Create cell array
SoilTypes = {'Soil A' 'Soil B' 'Soil C' 'Soil D'};
% Set the string property of the popup menu:
set(handles.popupenu1,'String',SoilTypes);
2) Now the callback you are talking about seems to be the Selection Change callback, which might look like this:
function Popupmenu1_SelectionChangeFcn(hObject, eventdata, handles)
This gets executed when the user changes the selected item in the popupmenu. Therefore, you want to get the selected item with this line:
get(handles.popupmenu1,'Value')
So according the the previous cell array, you can use (among other options) a switch/case scenario in which you can do whatever stuff you want for every type of soil, such as displaying text in the static text box. You can also set directly the string in the text box like so:
SelectedItem = get(handles.popupmenu1,'Value') % Get the value, from 1 to 4 in your case
set(handles.text1,'String',SoilTypes{SelectedItem}); % Display the corresponding soil type
Hope that helps get you started!
I have a GUI with an edit box and a push button on the tool bar (well, more things than that, but those are the only things that matter!) Anyway, I have it so when you press the push button tool a variable is set to equal the string in the edit box. A simple var = get(handles.edit1, 'string'). However, when I go straight from entering the value in the box to clicking the pushbutton (without clicking anywhere else or pressing return), var is assigned the previous value in the edit box. Why is this? Is there any way to make sure the push button tool will pick out the correct value?
The GUI was made using guide, if that matters.
This is happening because the uipushtool callback is executing before the text box has time to 'validate'. There is surely a more elegant way to do that but this trick works:
You can use the waitfor command to tell the uipushtool callback to wait for the editable box to validate its input. Unfortunately is is not exactly enough so we'll have to:
1) pass the focus to a dummy control (I created a dummy pushbutton named pushbutton1 which does nothing. The focus could be send to any other dummy control.
2) now wait for the text box to validate its content.
3) When the text box is done, then retrieve the content the traditional way.
This method requires:
- A dummy control to send the focus to (but you can use a real one too)
- An dummy (or not) callback function for your editable box. (the waitfor instruction will wait for the callback to finish, if there is no callback, it will error
function uipushtool1_ClickedCallback(hObject, eventdata, handles)
uicontrol( handles.pushbutton1 ) ; %// pass the focus to a dummy control
waitfor(handles.edit1,'String'); %// wait for the editable box to validate its content
var = get(handles.edit1, 'string') ; %// now retrieve the editable box content
set( handles.text1 , 'String' , var ) %// this can be deleted, just to verify the method
% --------------------------------------------------------------------
function edit1_Callback(hObject, eventdata, handles)
%// This is the dummy callback function for the editable box
%// Do absolutely nothing here (or do if you want ... your choice)
EDIT
as I feared, my initial solution was too dirty to be robust enough. With 2 (or more) textboxes, I tried a large number of things but without success. I dropped the waitfor, I noticed that in some case, when the uipushtool was pressed, the callback of the editbox would fire but the uipushtool would not execute at all ... so i tried to managed things directly from the editbox callback => from the editbox keypressedFcn send each character as we type to a variable ... but even this editbox callback doesn't know the content of the edit box at the time it is executed ?? (This link provide a very simple example to reproduce that).
So to my great own disappointment, I had to resort to an 'external' solution. (If you accept that it becomes very simple though). The trick is to retrieve the handle of the Java EditBox object. Once we have the handle, getting the "real time" content is just matter of converting the Java string into a Matlab string.
To retrieve the Java object handles, you need the function FindJObj from Matlab central.
Put that anywhere in your matlab path, then the code for your pushbutton become something like :
To make sure there was no interferences between the text boxes and the uipushtools I made 2 separate uipushtools each controlling 1 editbox
function uipushtool1_ClickedCallback(hObject, eventdata, handles)
jEditbox = findjobj(handles.edit1); %// get the handle of the java editbox #1
var = char(jEditbox.getText) ; %// retrieve Java string and convert it to matlab string
disp(['uipushtool1_ClickedCallback running. Textbox1 content = ' var ]) %// debug line, you can delete or comment that
% --------------------------------------------------------------------
function uipushtool2_ClickedCallback(hObject, eventdata, handles)
jEditbox = findjobj(handles.edit2); %// get the handle of the java editbox #2
var = char(jEditbox.getText) ; %// retrieve Java string and convert it to matlab string
disp(['uipushtool2_ClickedCallback running. Textbox2 content = ' var ]) %// debug line, you can delete or comment that
Thanks to Yair Altman for the findjobj function, and many other contributions for Matlab users.
I tried to replicate your problem and created a new GUI using guide with only a pushbutton and an edit field. If I set the button callback to:
function pushbutton1_Callback(hObject, eventdata, handles)
get(handles.edit1,'string')
it always prints the current value of the edit field, no matter if I click somewhere else after entering the value or not. Which version of Matlab are you using? I've tested it using Matlab 2010a.
I am just starting to learn about push buttons and i am stuck. I have two pop up menus. When the user selects the push button. the total from each pop up menu selection is returned to the user. I got the values from the pop up menu but I dont know how to return it after the push button is executed. Any help is appreciated
function pushbutton1_Callback(hObject, eventdata, handles)
math=0;
data1 =get(handles.popupmenu1, 'Value') %processing data from first pop up menu
if data1== 1
math=1
elseif data1 == 2
math=4
end
data2=get(handles.popupmenu2, 'Value') %processing data from second pop up menu
if data2==1
math=math + 5;
end
% I tabulated math which is some number. I want to return it back to the user
in a text outside of the button.
There is another way then returning the value: You pass and store it within the guidata-structure. Search for guidata in the docs for detailed information. One example from the docs:
function My_Callback()
% ...
% Get the structure using guidata in the local function
myhandles = guidata(gcbo);
% Modify the value of your counter
myhandles.numberOfErrors = myhandles.numberOfErrors + 1;
% Save the change you made to the structure
guidata(gcbo,myhandles)
Short explanation how to do it:
1. get the data by myhandles=guidata(handle_of_the_figure)
2. add/modify data, like myhandles.Test = 123
3. dont forget to save the changes, otherwise they will "just disappear"-> use guidata(handle_of_the_figure,myhandles)
4. to test it, just load the guidata afterwards within another function and look for the changes!
EDIT
while re-reading your question, it came to my mind, that you perhaps just want a value calculated within your callback to be displayed somewhere else. for example, if you want the value showing up in an text-edit uicontrol, you can use:
set(HandleOfTheTextEdit, 'String', num2str(mat))
A more elaborate, but more powerful way would be to create your own handle class.
Doing that you could add callbacks to custom data. I did an example here.
I have a GUI that I want to add a popup menu to it.
The popup menu fields that should be shown are saved in the file targets.txt.
When I open my program, I want the popup menu to include the lines from the mentioned file above.
I'm doing this because I want the popup menu to change dynamically in the program. Since it will include directories paths that the user entered in another field, I'm saving the directories paths in a file, and each time a user enters a folder, I set the popup menu according to the file. (I did it and it works fine)
Since function myFunction_OpeningFcn(hObject, eventdata, handles, varargin) is called only after calling the "create function" of each component of the GUI, I couldn't do the initialization in the "opening function" of the program. Instead, I had to to something like this:
function databaseMenu_CreateFcn(hObject, eventdata, handles)
if ispc&&isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
handles.databaseMenuObject=hObject; % (1) see below
guidata(hObject, handles);
(1): I save the popup menu object in handles so that I can use it in the opening function.
And then, in the opening function I can do:
fid_r = fopen('targets.txt', 'r');
C = textscan(fid_r, '%s');
set(handles.databaseMenuObject,'String', C{1});
So, when someone adds a new "database" folder in the program, the popup menu changes (I add the folder that was chosen by the user to the file, and then I set the popup menu to have its field from the file (the function above). So it'll look like that:
I don't like the design of my code, and I couldn't figure out how to do it in a different way, is there a way to make the "create function" of the "popup menu" to be called after the "opening function" of the program? Or is there a better way to achieve my goal?
Background
A few things that may be helpful:
You can define additional functions as needed within a GUI; you are not limited to the callbacks defined.
Tagging figure elements makes them easy to find from any callback.
gcbf returns the current callback figure.
union can return the union of cell arrays of strings.
Suggestions
Here is how I might write such a function. This puts everything in one place, the function can be called from anywhere within your GUI, it automatically updates the cached list, and eliminates any duplicate entries.
You would call this code at the end of your init code, as well as the callback for adding folders. The Tag can be set by right-clicking and setting properties within GUIDE.
updatePopupMenu()
popupMenuHandle = findobj(gcbf,'Tag','myPopupMenuTag');
popupMenuContents = get(popupMenuHandle,'String');
% Initialization
if isempty(popupMenuContests)
fid_r = fopen('targets.txt', 'r');
C = textscan(fid_r, '%s');
popupMenuContents = C{1};
end
% Join
otherFields = howeverYouGetFieldsFromOtherList();
combinedContents = union(popupMenuContents, otherFields);
% Save
set(popupMenuHandle,'String', combinedContents);
fid_w = fopen('targets.txt','w+');
for i = 1:length(combinedContents)
fprintf(fid_w,'%s\n',combinedContents{i});
end
fclose(fid_w);
end
Alright I now understand what you want to achieve, though I am not sure whether I understand the problem I hope this helps:
Judging from the description this seems like a logical order for things to happen:
1: Initalization, just initialize everything, you already know that you will have a dropdown menu but you just don't know the content yet. Therefore just start with a defaultoption or empty (possibly invisible).
2: Update, As soon as the users saves new input, you update the list.
I need to add/delete numerical values presented in the list box of MATLAB guide after selecting the number of values by the user. Also i need to update the listbox values using push button pressed
Somewhere in your opening function, before the line guidata(hObject, figure1), you should have some variable to keep track of your numbers. Declare something like
handles.numbers = {};
In general, if you have a cell array, cell_array, you can set the listbox like this. In the call back for your push button, first update the cell array and then load it into your list box using this line
set(handles.tag_of_listbox, 'String', handles.numbers, 'Value', 1);