“Nearest neighbor”-like interpolation in MATLAB

这一生的挚爱 提交于 2019-12-23 17:41:08

问题


This is a small thing but has been bothering me for a while now, so I thought I would let the crowd solving begin :)

I have a matrix with timestamps and a corresponding logical value (or 1/0), i.e.

of = [-inf 0 10 15 190 inf; 1 0 0 1 1 0]'

and an another time vector, e.g.

t = 0:0.1:1e3;

or whatever, you get the point :)

Now how do I (read: would you) inter-/extrapolate the logical infomation in of so it matches the timestamps in t, but with the interpolated logicals always assuming the last or current value, not a future one?

Don't know if that makes sense, but here is the expected output given of and t2

t2 = [0 5 14 16]
output = [0 0 10 15; 0 0 0 1]'

where the first column of output is the time of of used in interpolation. If I use interp1 and the 'nearest' algorithm, it will give

interp1(of(:,1), of, t2, 'nearest')
output = [0 10 15 15; 0 0 1 1]'  

which is not exactly what I want.


回答1:


Assuming your vectors are sorted you could try that, which seems to work with your example although I did not tested it extensively:

of=[-inf 0 10 15 190 inf; 1 0 0 1 1 0]';
t2 = [0 5 14 16];
index=floor(interp1(of(:,1),(1:size(of,1))',t2'));
output=of(index,:);

Hope it helps.

The default method used by interp1 is linear, which works best with your condition because you do not want the "nearest" neighbor but the first lower or equal neighbor (as far as I understand this). Therefore a simple truncation of the interpolated timestamps index gives you the result.



来源:https://stackoverflow.com/questions/7308878/nearest-neighbor-like-interpolation-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!