is it possible to use "find" to process every element of an array without loop

2 Ansichten (letzte 30 Tage)
Hi guys,
There is an array, saying a1, a2, ..., an.
For every element in the array, I want to do something like find(X<ai), where "X" is another array.
Is it possible to do it without loop and "cellfun"?
It seems cellfun is very slow.
Or maybe another way even not using find?
Thanks,
Zhong
  1 Kommentar
Daniel Shub
Daniel Shub am 11 Mai 2012
So for every element of array a you want a list of the elements of array X that are less than the current element of a and you want to do this without a loop? How big are your a and X? I would bet a loop working on a sorted X and a would be super fast.

Melden Sie sich an, um zu kommentieren.

Antworten (3)

Andrei Bobrov
Andrei Bobrov am 11 Mai 2012
eg:
a = randi(9,7,1);
X = randi(9,12,1);
solution:
[I,J] = find(bsxfun(@lt,X,a.'));
out = accumarray(J,I,[],@(x){x});
  2 Kommentare
Jonathan Sullivan
Jonathan Sullivan am 11 Mai 2012
I must say, that is a very slick solution!
I think you might have missed a close parenthesis at the end of your last line. It should read:
out = accumarray(J,I,[],@(x){x});

Melden Sie sich an, um zu kommentieren.


Daniel Shub
Daniel Shub am 11 Mai 2012
I know it has a loop, but what about something like this:
a = randperm(1e5);
X = 2e3*randn(1, 1e5);
[b, ai] = sort(a);
[Y, Xi] = sort(X);
z = cell(size(a));
for iz = 1:length(z)
ii = find(Y<b(iz));
z{ai(iz)} = Xi(ii);
jj = 0;
if ~isempty(ii)
jj = max(ii);
end
Y = Y((jj+1):end);
Xi = Xi+jj;
end
Even with two "big" vectors, the code completes pretty fast. Given I take the time to sort the data, I bet there is a way to optimize the find and get even faster performance.

Honglei Chen
Honglei Chen am 11 Mai 2012
I don't know what your intention is, but for an array, you want to use arrayfun

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by