문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top