How can I find index of element in array?
3 919 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Mykhailo Yaroshenko
le 8 Nov 2017
Réponse apportée : RONG
le 4 Août 2024
I know that I have a number 5 as an element in array X, but I do not know its index. Does MATLAB have a built-in function similar to Python's "index" method for finding the index of an element in an array?
0 commentaires
Réponse acceptée
James Tursa
le 4 Sep 2024
Modifié(e) : MathWorks Support Team
le 5 Juin 2024
To find the index of a specific integer value (without roundoff error) in an array of integers, use the "find" function and == operator. For example, find the index of an element equal to 5 in a 1-by-11 vector of integers.
x = 0:1:10;
k = find(x==5)
To find a numeric value in an array of floating-point numbers, use a tolerance value based on your data. Otherwise, the result is sometimes an empty matrix due to floating-point roundoff errors. For example, find the index of an element equal to 0.5 within a roundoff error of 1e-6.
y = 0:0.1:1;
k = find(abs(y-0.5) < 1e-6)
7 commentaires
Ehsan Partovi
le 2 Oct 2021
The function find() is useful as far as matrices (2-D tensors) are concerned. I cannot, however, find a useful function for nd-arrays where, for instance, the index could be an array on its own. See example below:
M = reshape(1:24, [2,3,4]);
indices = index_finder(M==20); % indices = vector of indices
It would be very useful if there was a function which worked for tensors of any dimensionality.
Jesse Ivers
le 29 Juin 2023
@Ehsan Partovi I couldn't agree with you more; this is a problem I seem to run into often, and here is my solution:
% Example ND-array
arr = reshape([1:6000], [5 5 10 4 6]);
numberOfInterest = 99;
% Get the linear index of the
linearIndex = find(arr==numberOfInterest);
% Convert linear index to subscript
[row, col, depth, channel, time] = ind2sub(size(arr), linearIndex)
The only drawbacks are the reuirement that you know how many dimensions. YOu can get around this with CSLs like so:
% Use CSL to get all the outputs
[idicies{1:ndims(arr)}] = ind2sub(size(arr), linearIndex)
Plus de réponses (2)
RONG
le 4 Août 2024
% Suppose X is your array
X = [3, 5, 7, 5, 9];
% Find the index of the element 5
index = find(X == 5);
0 commentaires
Voir également
Catégories
En savoir plus sur Matrices and Arrays dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!