How I can find index of element in array?

5 383 vues (au cours des 30 derniers jours)
Mykhailo Yaroshenko
Mykhailo Yaroshenko le 8 Nov 2017
Commenté : Jesse Ivers le 29 Juin 2023
I know, that number, for example, 5, is an element in array X, but I don't know it's index. In Python, I can use:
X.index(5)
I realized this function, using for loop and if statement, but did Matlab doesn't have build-in similar function?

Réponse acceptée

James Tursa
James Tursa le 8 Nov 2017
Modifié(e) : James Tursa le 8 Nov 2017
If you know the number exactly, then you can use:
result = find(X==5);
  7 commentaires
Ehsan Partovi
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
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)
row = 4
col = 5
depth = 4
channel = 1
time = 1
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)
idicies = 1×5 cell array
{[4]} {[5]} {[4]} {[1]} {[1]}

Connectez-vous pour commenter.

Plus de réponses (0)

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!

Translated by