Reputation: 10139
Is there a fatser way to xor every column of a matrix than this?
mod(sum(matrix),2)
It converts from logical to double and uses the expensive modulo.
Update:
According to this source, summing uint's is slower than summing doubles because it involves max clipping and other reasons.
Also, note that summing logicals (with 'native'
) stops at 1.
Upvotes: 3
Views: 3042
Reputation: 5251
In addition to what @ClementJ says, I tried
tic
E = A(1)
for i = 2:numel(A)
E = xor(y, A(i));
end
E
toc
hoping the accelerator would help, but it doesn't (much), and
tic
F = num2cell(A);
F = xor(F{:})
toc
which doesn't actually work because XOR only allows 2 inputs.
MATLAB's double precision vector arithmetic is about as fast as it gets, so you probably can't do better. If this is really driving your performance, then I suggest writing a C-MEX function: should be easy.
Upvotes: 1
Reputation: 3032
I tried to avoid the cast to double
but it's not better (often worse).
A = rand(2000000, 1) > 0.5;
class(A)
tic
B = mod(sum(A),2)
toc
tic
C = mod(sum(uint32(A),'native'),2)
toc
tic
D = bitand(sum(uint32(A),'native'),1)
toc
The native
option of sum allow you to keep the type of the argument in the result.
Upvotes: 2