How it is possible to pass variables from the script into a Callback function?

I have written the following code in which couple of checkboxes will be generated on a plot.
Now, I want to make it in a way that for every checkbox, a specific plot is being shown if the checkbox is checked by the user.
The problem is I can not use the variables such as my loop index inside the Callback function.
I would appreciate if someone could help me.
for i=1:AnSwer
cellwithstruct=d.channels(i);
chkbox=uicontrol('Style','checkbox','String',cellwithstruct{1}.name,'position',[10 25*(i-1) 60 20], ...
'Callback',@myCallbackfunc);
plot(time_vector,d.samples(i,:));grid minor;%This is the plot that I want to use inside the Callback function
end
The format for callback function is:
function myCallbackfunc(hObject, ~, ~)
if (get(hObject,'Value') == get(hObject,'Max'))
%The plot should be done here;
else
%The plot should be erased here;
end
end

4 Comments

You can either make your callback a nested function or just pass the further arguments in e.g (off the top of my head without testing).
@(src,evt) myCallbackfunc( src, time_vector, d, i )
function myCallbackfunc(hObject, time_vector, d, i )
if (get(hObject,'Value') == get(hObject,'Max'))
plot( time_vector,d.samples(i,:));grid minor;
else
%The plot should be erased here;
end
end
Being able to delete the relevant plot is more tricky. Personally I almmost always do these things in a class so I have access to all the things I need just by passing the class in. In your case you could do this again using a nested function and creating an array of (initially empy) plot handles in your main code and assigning to the array when you call plot.
Using the above method it is less simple though.
"The problem is I can not use the variables such as my loop index inside the Callback function."
Why not? The MATLAB documentation explains how:
You could define use nested functions, or an anonymous function, as Adam showed:
'blahblahcallback',@(src,evt) myCallbackfunc(src,A,B,C)
or use the compact and efficient syntax shown in the help:
'blahblahcallback',{@myCallbackfunc,A,B,C}
Dear Adam,
Thank you very much. Very useful!

Sign in to comment.

Answers (0)

Categories

Find more on Graphics Performance in Help Center and File Exchange

Asked:

on 4 Jul 2019

Commented:

on 4 Jul 2019

Community Treasure Hunt

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

Start Hunting!