finding index of several values within a vector efficiently
2 次查看(过去 30 天)
显示 更早的评论
I am trying to find the index of 'several' values within an array/vector. For instance, I have a vector [1 2 5] and matrix X=[1 5 4 3 2]. I want it to return [1 5 2]. I could write a for loop that finds each values in that vector such as find(X==1), then find(X==2) ..., but I was hoping there is a vectorized way to do this. Thanks.
0 个评论
采纳的回答
the cyclist
2012-12-2
v = [1 2 5];
X = [1 5 4 3 2];
[tf loc] = ismember(v,X);
"loc" is the vector you want.
0 个评论
更多回答(1 个)
Matt Fig
2012-12-2
编辑:Matt Fig
2012-12-2
idx = [1 2 5];
X = [1 5 4 3 2];
vals = X(idx) % linear indexing.
2 个评论
the cyclist
2012-12-2
If I am interpreting Jimmian's question correctly, this method only gives the correct answer to the example because of a numerical coincidence. For example, if
X = [0 0 0 0 0 1 5 4 3 2]
then I think he wants the output to be
loc = [6 10 7]
and not
[0 0 0].
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!