Info

This question is closed. Reopen it to edit or answer.

GUI and dealing with functions

1 view (last 30 days)
Alex Dytso
Alex Dytso on 25 Jun 2012
Closed: MATLAB Answer Bot on 20 Aug 2021
Hello, I am new to the GUI and I have a problem is that very basic. The question is regarding dropdown menu. When I select a value in dropdown menu lets say 3 and assign it to some variable lets say K. I want it to be used in other functions but other functions don't see it. I tried global variable but that doesn't work.
Can you help me. Thank you

Answers (2)

Image Analyst
Image Analyst on 25 Jun 2012
If you're using GUIDE, you'd do
global K;
K = get(handles.popmenu1, 'Value');
and then put global K; into every other function that needs to see K. Did you do that?
Or else you can just use that "get" line in every other function that needs K and forget about setting it to a global variable, as long as that function can see the handles structure, which all call backs can. If you need it in a function you wrote, a non-callback function, then you'd have to pass handles in via the argument list.
  2 Comments
Alex Dytso
Alex Dytso on 25 Jun 2012
Thank you for your response. So what I do is define:
global K;
K=3;
and then inside the definition of my funtion I put K as an argument
function myfunction(K)
I feel like I'm making a very fundamental mistake.
Image Analyst
Image Analyst on 25 Jun 2012
No. If it's global, you don't need to pass it via arg lists anymore. Just declare it global again inside any function that needs to "see" it.
function myfunction()
global K;
try
% Your code goes here
catch ME
errorMessage = sprintf('Error in myfunction().\nThe error reported by MATLAB is:\n\n%s', ME.message);
uiwait(msgbox(errorMessage));
end

John
John on 25 Jun 2012
you can either, as Image Analyst states, get(handles.dropdownmenu1,'Value') during each function or you can simply store it in the structure handles.
For example if the name of the dropdown menu is dropdownmenu1. then:
handles.value = get(handles.dropdownmenu1,'Value');
%Also add the following line at the end of the function
guidata(hObject,handles)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Now 'handles.value' should be accessible to every other function.

Community Treasure Hunt

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

Start Hunting!