Post Image
By Matt GaidicaJuly 5, 2016In Uncategorized

Finding Nearest Value in MATLAB Using min()

I’m often converting between samples or video frames and time. For example, I’ll have some video of animal behavior and an electrophysiological recording that each run on their own clocks (e.g. 30 frames-per-second for video and 30,000 samples-per-second for ephys). Therefore, it makes a lot of sense to use some absolute unit (like seconds) in the software so frame or sampling rates can disappear. This does create some syncing issues, when say, you want to find a video frame that occurs at t = 2.3539 seconds based on ephys events and your frame rate only resolved frames at t = 2.3333 and t = 2.3666. Given an array of values and a target value, this function returns the nearest index within that array, and the value which is nearest the target value.

Let’s use my example and create an array of thirty values between 2 and 3:

frameTimes = [2, 2.0345, 2.069, 2.1034, 2.1379, 2.1724, 2.2069, 2.2414, 2.2759, 2.3103, 2.3448, 2.3793, 2.4138, 2.4483, 2.4828, 2.5172, 2.5517, 2.5862, 2.6207, 2.6552, 2.6897, 2.7241, 2.7586, 2.7931, 2.8276, 2.8621, 2.8966, 2.931, 2.9655, 3];

And now we can use that stupid-simple function to find a nearest index and value:

[idx, val] = closest(frameTimes,2.3539);

Here’s the output and a figure to show what’s going on:

idx =
11
val =
2.3448

Now, I would know that whatever important thing happened at 2.3539 seconds can probably be revealed by looking at frame 11, or 2.3448 seconds into my video.

svgHuman Readable Bytes in MATLAB
svg
svgSurgical Tool for Cranial Drill Alignment in Rodents