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!