Find indices of points in meshgrid-like data

55 ビュー (過去 30 日間)
Aleksander Marek
Aleksander Marek 2018 年 9 月 26 日
コメント済み: Aleksander Marek 2018 年 9 月 27 日
Hi,
I'm looking for an optimal solution to the following problem:
You are given a vector containing coordinates x,y for set of points e.g.:
A = [2 3; 3 4; 1 1];
given that the full-data is structured in a matrix form (meshgrid-like)
[X,Y] = meshgrid(1:5, 1:5);
find indices B, such that:
A = [X(B), Y(B)];
I am able to solve this problem simply by looping over all points in A and finding the index with
for pt = 1:size(A,1);
index(pt) = find(A(pt,1)== X & A(pt,2) == Y);
end
However I'm not satisfied with the performance of this solution as I am running through ~50,000 data points around 300 times, and I'd love to replace the for loop with some vectorized formula.
Any help would be highly appreciated!
Thanks,
Alex

採用された回答

Adam
Adam 2018 年 9 月 26 日
[~, index] = ismember( A, [X(:) Y(:)], 'rows' );
Not sure if that is any faster than a loop though. ismember is not a very performant function as, if I remember correctly, it contains quite a lot of checks that slow it down.
  1 件のコメント
Aleksander Marek
Aleksander Marek 2018 年 9 月 27 日
It actually works really well, and gives improvement of about 10 times over the for loop.
Thanks a lot!

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

その他の回答 (1 件)

Bish Erbas
Bish Erbas 2018 年 9 月 26 日
How about this?
A = [2 3; 3 4; 1 1];
[X,Y] = meshgrid(1:5, 1:5);
XIdxCell = arrayfun(@(x) find(X==x),A(:,1),'UniformOutput',false);
YIdxCell = arrayfun(@(x) find(Y==x),A(:,2),'UniformOutput',false);
XIdx = cell2mat(XIdxCell);
YIdx = cell2mat(YIdxCell);
A = [X(XIdx), Y(YIdx)]

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by