Find the indices of numbers that occur first
3 views (last 30 days)
Show older comments
X is an array. Find(X, n, 1) gives the index of the first "n" that occurs. Now what of instead of "n" I have a vector like V = [n l m o ...]? The elements of V are unique.
1 Comment
Steven Lord
on 7 Oct 2024
Find(X, n, 1) gives the index of the first "n" that occurs.
No, it doesn't.
help find
find(X, n) would find the first n non-zero elements in X. 1 is not a valid value for the direction input argument.
Now if n is an integer or something that you know for a fact is in X you could use find(X == n, 1). If you're using release R2024b and have an n that is in or "close to" a value in X you could use find(isapprox(X, n), 1).
x = 0:0.1:1;
y = x(randi(numel(x), 100, 1));
loc = find(isapprox(y, 0.3), 5) % find the first 5 values in y that are approximately 0.3
y(loc)
Answers (3)
Walter Roberson
on 7 Oct 2024
[found, idxV] = ismember(X, V);
This will return the idx of elements of X within V; found(K) will be false if X(K) does not match any elements of V, and otherwise idxV(K) will be the index within V for X(K)
Closely related to this is
[found, idxX] = ismember(V, X);
which returns the index within X of the elements of V
1 Comment
DGM
on 7 Oct 2024
e.g.
% inputs
v = [0 1 2];
x = randi([0 3],1,10)
[vinx,idx] = ismember(v,x)
Matt J
on 7 Oct 2024
Edited: Matt J
on 7 Oct 2024
You won't be able to do better than a for-loop over the V(i).
3 Comments
Steven Lord
on 7 Oct 2024
Actually, I wanted to avoid a for loop.
Why? [If the answer is that you've been told "for loops are slow in MATLAB", tell whoever told you that that it is not really true anymore.]
Star Strider
on 7 Oct 2024
That is not an appropriate find call. The syntax is incorrect.
X = randperm(9) % Unique Random Vector
idx = find(X, 2, 1)
What do you want to do?
.
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!