Bowecho
Bowecho

Reputation: 909

Find closest value between time vectors of different lengths in MATLAB

I have 2 vectors, v1 and v2, containing date and time data. The vectors have different lengths, with length(v1)=15 and length(v2)=6. I want to obtain a new vector, v3, containing the closest values between v1 and v2, so I can accurately match the dates and times within v1 and v2. Does anyone have any idea how to achieve this? Thank you.

Upvotes: 1

Views: 705

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112689

To find the closest value in v1 to each element of v2:

v1 = [1 3 5 3 4];
v2 = [4 5 6];                                               % // example data
[~, ind] = min(abs(bsxfun(@minus, v1(:), v2(:).')), [], 1); %'// compute all differences
                                                            % // and find index of minimizer
result = v1(ind);                                           % // build result

In this example,

result =
     4     5     5

Upvotes: 2

Related Questions