Finding the index of elements of a vector in a mesh quite fast

1 回表示 (過去 30 日間)
Mohammad Shojaei Arani
Mohammad Shojaei Arani 2022 年 6 月 7 日
Hello friends,
I would like to find the index of vector of numbers A being closest in a mesh. I know how to do this but I hope you have a better idea to speed up the calculations.
An example: Consider a mesh of 10^6 regularly spaced numbers in the interval [0 10] and 10^4 random points A in this interval and we wish to find their corresponding index in our mesh (in the sense of being closest).
mesh=linspace(0,10,10^6);
A=0+(10-0).*rand(1,10000);
N=1000;
tic;
for n=1:N
ind=interp1(A,1:length(A),mesh,'nearest');
end
t=toc;
t/N
ans =
0.016923
So, on average it takes around 0.016923 seconds. I think that there should be a very smart way to do the same task with a much reduced computational time.
Any idea is greatly appreciated!
Thanks in advance,
Babak
  2 件のコメント
Torsten
Torsten 2022 年 6 月 7 日
Shouldn't it be
ind=interp1(mesh,1:length(mesh),A,'nearest');
instead of
ind=interp1(A,1:length(A),mesh,'nearest');
?
Mohammad Shojaei Arani
Mohammad Shojaei Arani 2022 年 6 月 7 日
Yes, of course. I was not carefull

サインインしてコメントする。

採用された回答

Torsten
Torsten 2022 年 6 月 7 日
編集済み: Torsten 2022 年 6 月 7 日
mesh=linspace(0,10,10^6);
A=0+(10-0).*rand(1,10000);
N=1000;
tic;
for n=1:N
y = discretize(A,mesh);
idx = A-mesh(y) >= mesh(y+1)-A;
y(idx) = y(idx) + 1;
end
t=toc;
t/N
ans = 0.0024

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by