How do I add a timer to a button push function that creates a scatter plot?

2 views (last 30 days)
I have a button push function right now that creates a scatter plot with randomly spaced dots and exes. I need to make a timer that starts when the button which plots the scatter plot is pushed and stops when another key such as 1 or 2 is pressed and records the time elapsed and I am not sure how to do this. Does anyone now how? Thanks in advance for your help!
function buttonPlot
% Create a figure window
fig = uifigure;
% Create a UI axes
ax = uiaxes('Parent',fig,...
'Xlim',[0 10], 'YLim',[0 10],...
'Position',[104, 123, 300, 201]);
%create tic toc timer? Not sure how do do this part
% Creat button push
btn = uibutton(fig,'push',...
'Position',[420, 218, 100, 22],...
'ButtonPushedFcn', @(btn,event) plotButtonPushed(btn,ax));
end
% Create the function for the ButtonPushedFcn callback
function plotButtonPushed(btn,ax)
x1 = rand(1,10)*10;
y1 = rand(1,10)*10;
x2 = rand(1,10)*10;
y2 = rand(1,10)*10;
scatter(ax,x1,y1,100,"green","filled","o")
hold(ax,'on')
scatter(ax,x2,y2,150,"red","+")
hold(ax,"off")
end

Accepted Answer

NIVEDITA MAJEE
NIVEDITA MAJEE on 29 Jun 2022
Edited: NIVEDITA MAJEE on 30 Jun 2022
Hi Peter,
I have made some modifications to your given code which displays the time elapsed between clicking of Start and Stop button.
function buttonPlot
% Create a figure window
fig = uifigure;
% Create a UI axes
ax = uiaxes('Parent',fig,...
'Xlim',[0 10], 'YLim',[0 10],...
'Position',[104, 123, 300, 201]);
%Text area to display elapsed time
textarea = uitextarea(fig,'Position',[420, 300, 100, 50]);
% Creat button push for start and stop
start_button = uibutton(fig,'push', 'Text', 'Start Plot',...
'Position',[420, 250, 100, 22],...
'ButtonPushedFcn', @(start_button,event) plotButtonPushed(start_button,ax));
stop_button = uibutton(fig,'push', 'Text', 'Stop Plot',...
'Position',[420, 218, 100, 22],...
'ButtonPushedFcn', @(stop_button,event) stop_timer(stop_button));
% callback fucntion for start button pushed
function plotButtonPushed(~,ax)
tic; %starts the timer
x1 = rand(1,10)*10;
y1 = rand(1,10)*10;
x2 = rand(1,10)*10;
y2 = rand(1,10)*10;
scatter(ax,x1,y1,100,"green","filled","o")
hold(ax,'on')
scatter(ax,x2,y2,150,"red","+")
hold(ax,"off")
end
% callback fucntion for stop button pushed
function stop_timer(~)
time = toc; %stops the timer
textarea.Value = sprintf("Elapsed time is %.3f seconds",time); %displays the time in seconds upto 3 decimal points
end
end
Hope this helps!

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!