Effacer les filtres
Effacer les filtres

Using find with a vector without having to use a for loop

2 vues (au cours des 30 derniers jours)
Matlab2010 le 14 Mar 2013
I have code which does
for t = 1: length(vector2)
idx(t) = find(vector <=vector2(t), 1, 'last');
Can I call find.m without using a for loop (or bsxfun.m) and if so how?
Or should I just use histc?
[~,idx]=histc(vector2, vector);
  5 commentaires
Jan le 14 Mar 2013
BSXFUN is not a slower version of a loop. I think ARRAYFUN could earn this description, especially when used with anonymous functions.
Matlab2010 le 28 Mar 2013
Having read more about this, I accept my previous statement is wrong and I was getting bsxfun confused with arrayfun.
it seems like bsxfun is what I need. thank you!

Connectez-vous pour commenter.

Réponse acceptée

Friedrich le 14 Mar 2013
Modifié(e) : Friedrich le 14 Mar 2013
use bsxfun and make sure one vector is a row vector and the other a column vector (a would be vector and b would be vector2)
a = [1 2 3 4 5 6]
b = [ 1 5 8 3 -10 2]
idx = bsxfun(@le,a',b)
Now you need to get a bit tricky I guess:
tmp = idx*(10.^[1:numel(b)]')
Not sure if maybe log2 would be faster, you would need to try it:
tmp = idx*(2.^[1:numel(b)]')
  2 commentaires
Jan le 14 Mar 2013
POWER and LOG10 are expensive functions. There must be a solution based on the integer indices also.
Jan le 14 Mar 2013
Yes! When the input vector2 (as in the original question) is sorted (and find(., 1, 'last') implies that it is), the logical matrix created by bsxfun contains zeros on the left and ones on the right (or top and bottom?). Then this matrix can be reshaped to a row vector and strfind searchs for [false true]. Finally the resulting indices must be cleaned up using mod() with the number of columns.

Connectez-vous pour commenter.

Plus de réponses (0)


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