Effacer les filtres
Effacer les filtres

Change function myfind (index)

3 vues (au cours des 30 derniers jours)
Cristian
Cristian le 11 Mai 2014
Modifié(e) : Cedric le 11 Mai 2014
I wrote the function myfind that return index of key:
function index = myfind(vec, key)
len = length(vec);
index = 0;
for i = 1:len
if vec(i) == key
index = i;
end
end
How to change the function to return a vector of indices of all occurrences of the key?

Réponse acceptée

Cedric
Cedric le 11 Mai 2014
Modifié(e) : Cedric le 11 Mai 2014
Using the same approach as you developed so far, you would have to build index as a vector:
index = [] ;
for k = 1 : len
if vec(k) == key
index = [index, k] ;
end
end
Don't use i as a loop counter, because it should be reserved to complex notation. Now if you want to optimize a bit the approach, without using FIND, look at the following example:
>> key = 3 ;
>> vec = randi( 5, 1, 10 )
vec =
1 5 5 3 5 1 3 5 4 5
>> isEq = vec == key
isEq =
0 0 0 1 0 0 1 0 0 0
>> allInd = 1 : length( vec )
allInd =
1 2 3 4 5 6 7 8 9 10
>> allInd(isEq)
ans =
4 7

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing 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