Get indices of matching values (vectorized find function)

I want to find a function that does a "vectorized find" that would do the below:
>> a = rand(6, 1)
a =
0.4387
0.3816
0.7655
0.7952
0.1869
0.4898
>> b = randi(6, [6, 1])
b =
3
4
5
5
2
5
>> c = a(b)
c =
0.7655
0.7952
0.1869
0.1869
0.3816
0.1869
>> b_reconstructed = somefunction(a, c) % What is somefunction?
I know I can do something like
b_reconstructed = zeros(size(a));
for i = 1:numel(c)
b_reconstructed(i) = find(a == c(i), 1, 'first');
end
But that seems very inefficient if a, b, and c are very large (>10k rows)

 採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 9 月 25 日

0 投票

Use ismembertol when dealing with floating point numbers, ismember when dealing with integers.
a = rand(6, 1)
a = 6×1
0.9147 0.9363 0.2163 0.6877 0.0031 0.8379
b = randi(6, [6, 1])
b = 6×1
4 1 3 1 5 4
c = a(b)
c = 6×1
0.6877 0.9147 0.2163 0.9147 0.0031 0.6877
B = zeros(size(a));
for i = 1:numel(c)
B(i) = find(a == c(i), 1, 'first');
end
B
B = 6×1
4 1 3 1 5 4
%Indices of elements in 'a' for each element in 'c' that is member of 'a'
[~,idx] = ismembertol(c,a)
idx = 6×1
4 1 3 1 5 4

1 件のコメント

Matt J
Matt J 2023 年 9 月 25 日
編集済み: Matt J 2023 年 9 月 25 日
However, tolerances shouldn't be necessary if it is known, as in the example, that c is an exact subset of a.

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

その他の回答 (1 件)

Matt J
Matt J 2023 年 9 月 25 日

0 投票

[~,b_reconstructed]=ismember(c,a)

カテゴリ

ヘルプ センター および File ExchangeMultidimensional Arrays についてさらに検索

製品

リリース

R2021a

質問済み:

2023 年 9 月 25 日

編集済み:

2023 年 9 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by