How can I check mouse events as a background process in Matlab? - 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

Related

MATLAB - AppDesigner: Interrupt a loop with GUI

I have created a GUI which computes a trajectory based on an external .m file.
When the user press the 'Calculate' button, the external .m function file gets called via the callback function of the button:
% calculateBtn button pushed function
function calculate(app)
numSteps = app.stepSlider.Value;
app.omega = app.omegaSpin.Value;
app.phid = app.phi.Value;
app.x0 = app.x0Spin.Value;
app.y0 = app.y0Spin.Value;
app.u0 = app.u0Spin.Value;
app.v0 = app.v0Spin.Value;
set(app.calculateBtn, 'Enable', 'off')
set(app.showBtn, 'Enable', 'off')
[app.Xc, app.Xi, app.C, T, f]=coriolis_traj(app.x0, app.y0, app.u0, app.v0, app.phid, numSteps);
app.fEdit.Value = num2str(f);
app.tEdit.Value = num2str(T);
set(app.calculateBtn, 'Enable', 'on')
if length(app.Xc)>1
set(app.showBtn, 'Enable', 'on')
else
set(app.showBtn, 'Enable', 'off')
end
end
The external file consists of the main loop of the computations.
while 1
% Counters
i = i + 1;
t = t + Dt;
theta = theta + Omega * Dt;
% Parcel's position
% on the inertial frame
x1 = x0 + Dt*u0;
y1 = y0 + Dt*v0;
% Parcel's position translated to the
% rotating frame
xc1 = x1*cos(theta)+y1*sin(theta);
yc1 = x1*sin(theta)+y1*cos(theta);
x(i) = x1 ; y(i) = y1;
xc(i) = xc1 ; yc(i) = yc1;
x0 = x1 ; y0 = y1;
[in] = inpolygon(xc,yc,xv,yv);
if ~in(i) > 0
break;
end
end
I want to stop the computation and clear the computed arrays when the user changes any of the values in 'Controls' panel, or when the button 'Break' is pushed.
How could I code this?
The best solution I can figure out is to bring your while loop inside your GUI callback. The inner code of your while loop can be kept on a separate, external file, but bringing in the loop will give you full control over it and will make it easier to interrupt. The only constraint is that it must be make less "tight"... it must contain a small pause (better if followed by a drawnow() call) so that the main GUI thread can have the time to process the application messages.
And here is the code of your callbacks:
% Computation Callback
function Button1_Callback(obj,evd,handles)
obj.Enable = 'off'; % disable this button
handles.Button2.Enable = 'on'; % enable the interruption button
handles.stop = false; % the control variable for interruption
while (true)
% call your external function for running a computational cycle
res = myExternalFunction(...);
% refresh the application handles
handles = guidata(obj);
% interrupt the loop if the variable has changed
if (handles.stop)
break;
end
% this allows the loop to be interrupted
pause(0.01);
drawnow();
end
obj.Enable = 'on';
end
% Interruption Callback
function Button2_Callback(obj,evd,handles)
obj.Enable = 'off'; % disable this button
handles = guidata(obj);
handles.stop = true;
end
There is no way in MATLAB to interrupt a function by another function, e.g. say programmatically injecting a CTRL-C into another running function, without modifying the to-be-interrupted function.
The closest you can get is by modifying the simulator code to regularly perform a callback. This is how I integrated by simulation code into a GUI. IMO it is a clean solution and also works with MEX files.
Think of it as a progress callback for your simulator code.
It could be regularly (e.g. every second, or at completion of the i-th step) called by the simulator with some percentage parameter to indicate the degree of completion.
If you modify the simulator code to stop simulating in case the callback returns false, you achieve what you want. At the same time this is minimum invasive in your simulator code. Supply a dummy callback and it will run stand alone.
GUI pseudocode:
function button_cancel_Callback(hObject, eventdata, handles)
global cancel_pressed;
cancel_pressed = true;
function dostop = callback( progress, handles )
<show progress>( handles.<XXX>, progress );
global cancel_pressed;
if cancel_pressed
dostop = true;
else
dostop = false;
end
function button_run_simulation_Callback(hObject, eventdata, handles)
global cancel_pressed;
cancel_pressed = false;
<simulator function>( ..., #callback, handles )
SIMULATOR pseudocode:
function <simulator function>( ..., callback, callback_param )
while ... % main loop
if ~isempty(callback) && ~callback( progress, callback_param )
error("canceled-by-user") % could also be something more elaborate
end
return "simulation completed"

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.

using timer in MATLAB to extract the system time

!I am using MATLAB to design an Analog Clock. Currently, my code simply displays the (or plots rather) the clock design with the hands (hours, mins, secs) and does not tick. Here is my code:
function raviClock(h,m,s)
drawClockFace;
%TIMER begins-------
t = timer;
t.ExecutionMode = 'FixedSpacing'; %Use one of the repeating modes
t.Period = 1; %Fire on 1 second intervals
t.TimerFcn = #timer_setup; %When fired, call this function
start(t);
set(gcf,'DeleteFcn',#(~,~)stop(t));
end
function timer_setup(varargin)
format shortg;
timenow = clock;
h = timenow(4);
m = timenow(5);
s = timenow(6);
% hour hand
hours= h + m/60 + s/3600;
hourAngle= 90 - hours*(360/12);
% compute coordinates for pointing end of hour hand and draw it
[xhour, yhour]= polar2xy(0.6, hourAngle);
plot([0 xhour], [0 yhour], 'k-','linewidth',7.4)
% minute hand
mins= m + s/60;
minsAngle= 90 - mins*(360/60);
% compute coordinates for pointing end of minute hand and draw it
[xmins, ymins]= polar2xy(0.75, minsAngle);
plot([0 xmins], [0 ymins], 'r-','linewidth',4)
%second's hand
second = s;
secAngle = 90- second*(360/60);
[xsec, ysec]= polar2xy(0.85, secAngle);
plot([0 xsec], [0 ysec], 'm:','linewidth',2)
%end % while ends
end
%--------------------------------------------------------
function drawClockFace
%close all
axis([-1.2 1.2 -1.2 1.2])
axis square equal
hold on
theta= 0;
for k= 0:59
[xX,yY]= polar2xy(1.05,theta);
plot(xX,yY,'k*')
[x,y]= polar2xy(0.9,theta);
if ( mod(k,5)==0 ) % hour mark
plot(x,y,'<')
else % minute mark
plot(x,y,'r*')
end
theta= theta + 360/60;
end
end
%-----------------------------------------------------------------
function [x, y] = polar2xy(r,theta)
rads= theta*pi/180;
x= r*cos(rads);
y= r*sin(rads);
end
This is simply taking a static data of values for the HOUR, MINUTE and SECOND arguments when i initially call my function. I tried using the following in a while loop but it didn't help much
format shortg
c=clock
clockData = fix(c)
h = clockData(4)
m = clockData(5)
s = clockData(6)
and passing the h, m and s to the respective cuntions. I want to know how I can use the TIMER obkjects and callbacks for extracting the information of [hrs mins secs] so i can compute the respective point co-ordinates in real time as the clock ticks.
I'd do a couple of things here.
First, you probably don't really need to pass the h, m, s inputs, if you are displaying current time. Add this to the top of your function to auto set these variables.
if nargin == 0
[~,~,~,h,m,s] = datevec(now);
end
Then, it is pretty easy to use a time to call this function periodically. Something like this.
t = timer;
t.ExecutionMode = 'FixedSpacing'; %Use one of the repeating modes
t.Period = 1; %Fire on 1 second intervals
t.TimerFcn = #(~,~)raviClock; %When fired, call this function (ignoring 2 inputs)
start(t); %GO!
Use docsearch timer for in depth documentation of the timer objects. But the code above should get you started.
To stop the timer, run
stop(t);
To stop the timer when the window is closed, put the stop command into the window deletion callback:
set(gcf,'DeleteFcn',#(~,~)stop(t)); %NOte: Better to explicitly use a figure number, rather than gcf.

Take user input while running in Matlab

I have a function that I would like to take input for but only when the user wants to. For example if i have this code:
figure
amplitude = 10;
tic
i = 1;
while(1)
time = toc;
values(i) = amplitude*sin(time);
times(i) = time;
plot(times, values)
drawnow
i = i+1;
end
You will get a continually plotting sine wave (like a lame movie). What I want to do is allow the user to change the amplitude of the wave at any time. That is the program will continue to run but if the user types in 20 and Enter then the amplitude variable can be changed and the sine wave will change amplitude in the movie. Any pointers on how to achieve this?
You won't be able to do this by typing numbers into the console, but you can do it with a simple GUI. Do a google search for Matlab callbacks to find examples. When a GUI event occurs, it triggers a function that you can use to modify the variables in your loop.
It is probably best to do it with a GUI as mentioned, but if you just want something in the console here is what I can offer:
A script that periodically asks the user to input an amplitude and then continues the 'movie' with this amplitude. It can easily be expanded to allow the user to decide when he will be asked to input the next amplitude change.
clear
amplitude = 10;
i=1;
while(1)
time = i/1000;
values(i) = amplitude*sin(time);
times(i) = time;
plot(times, values)
drawnow
i = i+1;
if mod(i,3141) == 0
keyboard
end
end
Now this will run for a while and then ask you to input the next amplitude. Note that you can actually give multiple commands at once.
amplitude = 20; return
amplitude = 1; return
This will let the next amplitude be 20 and the one after that 1. Note that the upward arrow key is your friend here.

Accept only one keypress for a certain period of time in Matlab

I have a simple, sort of GUI code shown below.
This "test_keypress" function creates a figure, and it responses to the keypress (space).
Now, I want to add a constraint so that Matlab accepts only one keypress for a certain period of time (say, 1 second).
In other words, I want to reject a keypress if it happens within 1 sec after the previous keypress occurred.
How can I do that?
function test_keypress
f = figure;
set(f,'KeyPressFcn',#figInput);
imshow(ones(200,200,3));
end
function figInput(src,evnt)
if strcmp(evnt.Key,'space')
imshow(rand(200,200,3));
end
end
You can store the current time, and only evaluate the imshow command if the key-press occurs at least 100 seconds after the last one.
function test_keypress
f = figure;
set(f,'KeyPressFcn',#figInput);
imshow(ones(200,200,3));
%# initialize time to "now"
set(f,'userData',clock);
end
function figInput(src,evnt)
currentTime = clock;
%# get last time
lastTime = get(src,'UserData');
%# show new figure if the right key has been pressed and at least
%# 100 seconds have elapsed
if strcmp(evnt.Key,'space') && etime(lastTime,currentTime) > 100
imshow(rand(200,200,3));
%# also update time
set(src,'UserData',currentTime)
end
end