MATLAB Answers

How can I run a stopwatch in MATLAB and store time points in a variable by hitting a key on the keyboard?

27 views (last 30 days)
Sarah
Sarah on 19 May 2017
Answered: Abhinav Gurram on 22 May 2017
I am collecting a continuous recording from a sensor, but I will only need certain segments of the recording. I want to use a stopwatch in MATLAB to record the start and stop times of the relevant segments of data from the sensor. I need a function that starts a timer when I push one key, then stores the timer value when I press another key and that stops the timer when I press a third key. I was going to use the tic and toc functions . . . how do I get MATLAB to store the time elapsed since the last tic when I hit a certain key on the keyboard? Thanks!

Answers (1)

Abhinav Gurram
Abhinav Gurram on 22 May 2017
As you rightly mentioned, the use of ' tic ' and ' toc ' functions seem best suited for your workflow. You can use any of the ways listed here: Ways to build apps to build an app, and have corresponding buttons for starting(tic) and stopping(toc) the timer. Furthermore, the 'tic' function can be used along with a variable to record time for simultaneous time spans. The variable, 'timerVal', has a value that is equal to the value of the internal timer at the execution of the 'tic' command. The 'tic' function can now be called as:
>>timerVal = tic
Afterward, you can use the 'toc' function to capture the elapsed time since the 'tic' command corresponding to 'timerVal' as:
>>elapsedTime = toc(timerVal);
You can associate the variable, 'elapsedTime' with a particular callback function that is executed when a keyboard key is pressed. The 'KeyPressFcn' might be a good way to capture the user's keyboard input. You can visit the following link for more information on how to write callbacks for apps:
  1. Write Callbacks for Apps Created Programmatically
  2. Write Callbacks in GUIDE
Hope this helps!

Community Treasure Hunt

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

Start Hunting!