find a vector in a big vector

hi! how could i write this:
%
index=[find(a=2);find(a=4);find(a=6);find(a=8)....find(a=20)]
in a compact manner?
thank you

 Réponse acceptée

José-Luis
José-Luis le 21 Fév 2013
Modifié(e) : José-Luis le 21 Fév 2013

0 votes

vals = (2:2:20)';
your_mat = cell2mat(arrayfun(@(x) {find(a==x)},vals,'uniformoutput',false));
And if you don't care about the order:
vals = (2:2:20)';
[ia ib] = ismember(a,vals);

4 commentaires

Rica
Rica le 21 Fév 2013
there is a problem with cell2mat!
Rica
Rica le 21 Fév 2013
i solve it in this way:
%
vals = (2:2:20)';
your_mat = (arrayfun(@(x) {find(a==x)},vals,'uniformoutput',false));
gg=cat(1,your_mat{:});
result=cell2mat(gg);
thank you!
José-Luis
José-Luis le 21 Fév 2013
My pleasure
Jan
Jan le 21 Fév 2013
Arrayfun with an anonymous function can be much (e.g. 10 times) slower than a corresponding simple FOR loop.

Connectez-vous pour commenter.

Plus de réponses (2)

Andrei Bobrov
Andrei Bobrov le 21 Fév 2013

1 vote

a = randi(80,50,1);
v = (2:2:20).';
[i1,i2] = ismember(a,v);
i3 = find(i1);
[~,jj] = sort(i2(i1));
index = i3(jj);
Jan
Jan le 21 Fév 2013
Modifié(e) : Jan le 21 Fév 2013

0 votes

Please compare the runtime of this simple loop with the compact ARRAYFUN function with an anonymous function:
search = [2,4,6,8,20];
C = cell(1, length(search));
for iSearch = 1:length(search)
C{iSearch} = find(a == search(iSearch));
end
result = cat(2, C{:});
If compactness of the code really matters, write this as a function.

Catégories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by