MATLAB: How to pass variable from popup menu to button

matlab pass variable

function popupmenu1_Callback(hObject, eventdata, handles)
contents=get(hObject,'Value');
switch contents
case 1
rgbImage=imread('lion.jpg');
axes(handles.axes1);
imshow(rgbImage);
case 2
rgbImage=imread('dog.jpg');
axes(handles.axes1);
imshow(rgbImage);
case 3
rgbImage=imread('ondel-ondel.jpg');
axes(handles.axes1);
imshow(rgbImage);
case 4
rgbImage=imread('house.jpg');
axes(handles.axes1);
imshow(rgbImage);
case 5
rgbImage=imread('jungle.jpg');
axes(handles.axes1);
imshow(rgbImage);
otherwise
end
function pushbutton2_Callback(hObject, eventdata, handles)
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
redFiltered = medfilt2(redChannel, [3,3]);
greenFiltered = medfilt2(greenChannel , [3,3]);
blueFiltered = medfilt2(blueChannel , [3,3]);
filteredRgbImage = cat(3, redFiltered , greenFiltered , blueFiltered );
axes(handles.axes2);
imshow(filteredRgbImage);
how to pass the rgbImage variable from popupmenu1 to pushbutton2?

Best Answer

robby, you can make the variable global in a few ways, like discussed in the FAQ. One way to make them global is to just attach the image to the handles structure. But you don't need to do any of that stuff you did in the "case 1" code you gave. Simply do
handles.rgbImage = rgbImage;
This will let it be global in any callback function (because they automatically get the handles structure), or in any function that you pass the handles structure to. Another way to make it global is to use global keyword.
global rgbImage;
It's not really global - not every function can see it. It's only seen by those functions that have that global line in them, just like doing it via the handles structure lets it be seen only by those functions that have access to the handles structure.
Since the variable is then global be aware that any changes you make to it will be seen by any function from then on - it's not like a local variable where you can make changes and then the changes are lost when the function exits.