Question

I have an array of elements and 2 other arrays
I'm doing something like this:

a=[1 3 2 45 4 23 16];
b=[3 9 1 27 33 50 5];
m=10;
k=linspace(min(a),max(a),m);
res=zeros(m,1);
for i=1:m
    res(i) = sum((a < k(i)).*(b < k(i)));
end

Is there any way to get the same result with no loops?

Was it helpful?

Solution

To remove the loop, you can use bsxfun, keeping the rest of your script:

res = sum(bsxfun(@lt,a',k).*bsxfun(@lt,b',k),1).';

Basically, it applies the operator less-than to the pairs of vectors (a,k) and (b,k); the transposition guarantees that you compare a column vector to a row one, leading to a matrix result. The reduction of the dot product is made along a specified direction (row direction). I transpose the result to have the same size as yours, but it is not mandatory.

OTHER TIPS

You could also use repmat:

a=[1 3 2 45 4 23 16];
b=[3 9 1 27 33 50 5];
m=10;
k=linspace(min(a),max(a),m);
for i=1:m
    res(i) = sum((a < k(i)).*(b < k(i)));
end
k=transpose(k);
k=repmat(k,[1,7]);
a=repmat(a,[m,1]);
b=repmat(b,[m,1]);
res2 = sum((a<k).*(b<k),2);

Note that res2=transpose(res)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top