How do I alter a variable with a uicontrol callback function? - matlab

The big picture goal is to successively plot an image sequence at some rate and pause the process when the pushbutton is pressed. Then resume the process upon hitting the space bar or pressing the pushbutton or whatever. Here is the code I have so far with a simple rand/pause(0.5) procedure for each iteration of the loop (instead of plotting my images).
My issue is this:
ButtonCallback seems to be invoked when the pushbutton is pressed, and DoPause is set to 1 in the callback function, BUT DoPause is not changed in the main function PauseButtonTest. How do I change this variable so the if statement in my while loop is executed.
Any help is appreciated. Thanks.
function PauseButtonTest
DoPause = 0;
hb = uicontrol('Style','Pushbutton','String','Pause','FontWeight','Bold', ...
'Callback',#ButtonCallback,'Unit','Normalized','Position',[0 0 1 1]);
while ishandle(hb)
if DoPause
disp('You pushed the button')
pause
DoPause = 0;
set(hb,'Enable','On')
drawnow
end
% Computations/Plot successive figures/etc.
rand
pause(0.5)
end
end
function ButtonCallback(hObj, event)
DoPause = 1;
disp('You are in ButtonCallback')
disp(['DoPause = ' num2str(DoPause)])
set(hObj,'Enable','off')
end

Nested functions.
Just move function ButtonCallback(hObj, event) ... inside PauseButtonTest so that it has access to its variables ("externally scoped" variables). Plop it down a couple of lines below the while loop and before the end that signals the end of PauseButtonTest.

Related

Matlab stop function's execution

I have an array. I am processing elements of this array in a for loop inside a function.
function results = processArray(array)
for ii = 1:length(array)
%some stuff here
results(ii) = %getting the results for this particular element
end
end
There might be a lot of elements and computations might take a lot of time. I want to be able to finish execution of the for loop at any arbitrary time when a user wants to do that so that the results for already processed elements would be available.
I was trying to make a figure with a button which would change a boolean flag. Inside the for loop I was checking the value of that boolean. If the boolean changed then the for loop should break.
function results = processArray(array)
fig = figure;
fig.UserData.continue = 1;
uicontrol('Parent', fig', 'Style', 'pushbutton', 'String', 'stop', 'callback', #interrupt)
for ii = 1:length(array)
if(fig.UserData.continue == 0)
break;
end
%some stuff here
results(ii) = %getting the results for this particular element
end
end
function interrupt(obj, ~)
fig = obj.Parent;
fig.UserData.continue = 0;
end
well, that does not work. The figure shows up only after all the computations are done already. If I draw the figure first using something like waitforbuttonpress and proceed to the for loop pressing the button does not stop the execution. I think the callback function is being executed only after the for loop is finished. Is there any way to solve this?
You will need to drawnow after you create the button, so it will show up. You also need to drawnow within the loop to update the button state. Then you should achieve what you want.
drawnow force figure update, so it will slow down your computation a little.

How can I check mouse events as a background process in Matlab?

I am using Matlab to develop an application which performs several mathematical operations, whose parameters can be changed when the mouse is clicked, as in the example below.
while time<endtime
calculate_manythings;
if ~mod(time,checkmouse)
mouseinput_timeout(timemouse, gca);
change_calculation_parameters;
end
time=time+1;
end
At the moment, I am pausing the operations periodically to check for mouse events, but this is slow and unpractical. How can I monitor these continually and run the code at the same time? Could I make the mouse event checks a background process using parfeval, for example?
Many thanks,
Marta
you can use callback functions. here I used 'ButtonDownFcn':
timeinterval = 1; % seconds between mouse clicks
% generate axes with callback function
h = plot(rand(1,2),'LineWidth',6);
set(gca,'ButtonDownFcn',#callback);
% reset Tag and time
h.Tag = '';
tic;
while true
drawnow;
if strcmp(h.Tag,'Pressed') % if pressed
t = toc; % check time passed
if t >= timeinterval
% change parameters
disp('Pressed');
h.Color = rand(1,3);
% reset timer
tic;
end
% reset Tag
h.Tag = '';
end
end
and the callback function is:
function callback(src,~)
src.Children(1).Tag = 'Pressed';
end

Matlab gui with pause function

I am using the GUIDE for matlab gui.
The gui built in order to communicate with keithley current measurement device through GPIB.
When using a toggle button for Current measurement while loop, i am using a pause() function inside the while loop for each iteration and a ytranspose on the y array reading results.
function Measure_Callback(hObject, eventdata, handles)
global GPIB1
global filename
global timeStep
disp('Measurement in progress \n stopwatch starts!');
tic
x=0;
n=0;
while get(hObject,'Value')
fprintf(GPIB1, 'printnumber(smua.measure.i(smua.nvbuffer1))');
fprintf(GPIB1, 'printbuffer(1,1,nvbuffer1)');
A = fscanf(GPIB1);
if length(A)<20
x = x+1;
n = n+1;
t(n) = toc ;
y(x) = str2double(A);
plot(t,y,'-bo',...
'LineWidth',2,...
'MarkerEdgeColor','k',...
'MarkerFaceColor',[.49 1 .63],...
'MarkerSize',10);
grid on
hold on
end
title('Current vs Time','FontSize', 15)
xlabel('Time [s]','FontSize', 15)
ylabel('Current [A]','FontSize', 15)
a = timeStep;
pause(a)
end
disp('Measurement terminated');
disp('Elapsed time: ');
elapsedtime = toc;
elapsedtime_string = num2str(elapsedtime);
disp(elapsedtime_string);
ytrans = transpose(y);
csvwrite(filename,ytrans);
fprintf(GPIB1, 'smua.source.output = smua.OUTPUT_OFF');
For the pause function i'm geting error:
?? Error using ==> pause Error while evaluating uicontrol Callback
For the transpose(y) function i'm also getting a error:
its undefined y.
Cant understand why are those errors and could use some help.
Thank you!
First off, as people say, post the errors and the code. Do you know if length(A) is smaller than 20 in the first time you run the loop? Because if not, A is not defined and you can't transpose something that is not there. Initialize A before the loop to something and see if the error persists (or print out length(A) to make sure the loop gets entered the first run).
As for the pause error, make sure pause is an int or double, not a string. If you get your global timeStep from the GUI field, it is probably a string and you need to covert it to double first.

Is this a race condition in matlab?

The title says it all. I was wondering if the following code is prone to a race condition.
classdef Foo < handle
properties
value = true
end
methods
function toggle(o, ~, ~)
o.value = ~o.value;
end
end
end
function main
foo = Foo;
uicontrol('style', 'pushbutton', 'callback',#foo.toggle);
drawnow
%// Endless loop which gets broken up by a button press
while foo.value
pause(1)
end
%// What happens if I press the button twice, really fast? There
%// is no external function called between here and the previous
%// while loop.
if foo.value
error('Race')
else
fprintf('\nWe made it\n')
end
Am I save from the race condition since everything happens in the event dispatch thread? Is the same still true if I play with Interruptible and BusyAction property of the button? I found the matlab help quite confusing.
In case it matters I'm using R2012a.

KeyPressFcn not working on specific occasions

I have a KeyPressFcn that seems to work whenever I'm obtaining new data and plotting it. When I'm not obtaining new data, the KeyPressFcn seems to no longer work. But if I do press the corresponding key, once I get back into data range and begin taking data again, it closes the figure.
I'm really confused why this is happening. My data collection happens only if a certain condition is met, but changing the KeyPressFcn and exitflag is inside my while loop and should be happening every time a loop occurs, thus I don't see why it wouldn't immediately exit my figure. Here is the code,
disp('DICOM Slice Viewer');
disp('" ": exit on space key');
global kpressed;
kpressed = 0;
%init figure on screen
global Fig;
Fig=DICOM_SliceViewer_createFigure(1,DICOMparam);
set(Fig.fig,'KeyPressFcn','global kpressed; global Fig; kpressed = get(Fig.fig,''CurrentChar'');');
exitflag = 0;
while (exitflag == 0)
Naviparam=Navi_acquire(Naviparam);
Naviparam=Navi_calc_data(Naviparam);
%calibration calculation !TO BE CHECKED!
DICOMPos = DICOMparam.calib.navi2dicom*[Naviparam.data.Endo_RefOffsetPosVec;1];
ixR=round(min(max(DICOMPos(1),1),DICOMparam.Sx));
iyR=round(min(max(DICOMPos(2),1),DICOMparam.Sy));
izR=round(min(max(DICOMPos(3),1),DICOMparam.Sz));
if kpressed ~= 0
switch kpressed
case ' '
exitflag = 1;
disp('**** Exit DICOM Slice Viewer ****')
end
kpressed = 0;
end
if Naviparam.datastr(5:11)~='MISSING'
%refresh plot with 3 standard cuts
set(Fig.sub1im, 'cdata', reshape(DICOMparam.Vd(ixR,:,:),[DICOMparam.Sy DICOMparam.Sz]));
set(Fig.sub2im, 'cdata', reshape(DICOMparam.Vd(:,iyR,:),[DICOMparam.Sx DICOMparam.Sz]));
set(Fig.sub3im, 'cdata', reshape(DICOMparam.Vd(:,:,izR),[DICOMparam.Sx DICOMparam.Sy]));
drawnow;
end
end
close(Fig.fig);
clear global;
Solved my own problem!
All I did was move the "drawnow" out of the if statement. This allowed me to draw my new data if it was taken, but also allowed some internal parameters to be updated in the figure I believe.