finding all indices of a value in matrix
Afficher commentaires plus anciens
i have a matrix say
[2 2 3 ;
2 4 2;
2 3 2]
how do i find all the indices (row, column) of 2 (minimum value element of matrix) in the given matrix?
4 commentaires
Look mum, no find !:
>> M = [2,2,3;2,4,2;2,3,2];
>> X = M(:)==min(M(:));
>> [R,C] = ndgrid(1:3);
>> R = R(X)
R =
1
2
3
1
2
3
>> C = C(X)
C =
1
1
1
2
3
3
sambhav jain
le 18 Fév 2020
Stephen23
le 18 Fév 2020
"but could you plz tell how is it better by not using find?"
It isn't better, it just demonstrates that every problem can be approached in different ways, and hopefully shows a different way to think about the problem.
sambhav jain
le 18 Fév 2020
Réponse acceptée
Plus de réponses (1)
Steven Lord
le 18 Fév 2020
Do you need the locations or do you simply need to refer to the locations where the specified value occurs? Those are two slightly different things. If the latter, you don't need to use find and don't need to compute the indices at all.
Use logical indexing.
A = [2 2 3 ; 2 4 2; 2 3 2]
B = A; % Make a copy of A for future reference
two = A == 2 % Create a logical mask
B(two) = -1 % Replace all 2's in (the copy of) A with -1
In this example, I don't care where the 2's were in A. I only cared that I could change those elements.
4 commentaires
sambhav jain
le 18 Fév 2020
Steven Lord
le 18 Fév 2020
In that case, call min with two outputs. Depending on which release of MATLAB you're using specifying the dimension as 'all' (to find the minimum value in the whole array) and asking for the 'linear' index may be an option.
sambhav jain
le 18 Fév 2020
sambhav jain
le 18 Fév 2020
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!