Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast xor array in matlab

Tags:

matlab

xor

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.

like image 236
cyborg Avatar asked Feb 02 '26 20:02

cyborg


2 Answers

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.

like image 53
Clement J. Avatar answered Feb 04 '26 15:02

Clement J.


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.

like image 30
Nzbuu Avatar answered Feb 04 '26 14:02

Nzbuu