Find the indices of numbers that occur first
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
Steven Lord
2024-10-7
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)
回答(3 个)
Walter Roberson
2024-10-7
[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 个评论
DGM
2024-10-7
e.g.
% inputs
v = [0 1 2];
x = randi([0 3],1,10)
[vinx,idx] = ismember(v,x)
Matt J
2024-10-7
编辑:Matt J
2024-10-7
You won't be able to do better than a for-loop over the V(i).
3 个评论
Steven Lord
2024-10-7
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
2024-10-7
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!