Vectorizing finding indexes
2 次查看(过去 30 天)
显示 更早的评论
hi, i have a vector X and a vector Y (both in ascending order). for every element in X i want the indexes of the values in Y between which this element lies. Actually, 1 index suffices (preferably the higher bound).
For example if have
Y=[0, 1, 2, 3, 4, 5]
X=[0.1, 2.5, 2.8, 4.1];
then I want to get as a result:
IND = [2 4 4 6]; %the higher bounds of the interval in Y in which the elements of X fall
I can do this with a for loop:
for ix=1:length(X);
IND(1,ix)=min(find(Y>X(ix)))
end
My question is whether it is possible to vectorize this, and how... Many thanks in advance!
0 个评论
采纳的回答
Walter Roberson
2012-6-24
[counts, tIND] = histc( X, Y );
IND = tIND + 1; %to get the higher index
Note that this has questionable results in the case where an X is exactly equal to a Y: it will return the bin number of the next Y. You could, though, correct for this with
t = (X == Y(tIND));
IND(t) = IND(t) - 1;
It is also possible to correct for it at the time of histc(), but the code becomes notably more difficult to read.
3 个评论
Walter Roberson
2012-6-24
While you are thinking about that, also think about what to do if an X is before or after all of the Y.
See the comments in http://www.mathworks.com/matlabcentral/answers/41814-interpolation-with-high-frequency-financial-data
更多回答(3 个)
Jamie Rodgers
2012-6-24
Try This: Your vector
Y=[0:1:1000];
X=[0.1, 2.5, 2.8, 4.1];
Vectorised code
Z1=arrayfun(@(a)intersect(Y,ceil(a)),X);
idx=arrayfun(@(x)find(Y==x),Z1);
Sargondjani
2012-6-24
1 个评论
Walter Roberson
2012-6-24
You are correct: the expressions given by Jamie and Andrei as of the time of my writing this comment, only work for integer Y. My histc() based code does not depend on Y being integer.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Object Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!