vectorization - how to vectorise an xor operation in matlab -
vectorization - how to vectorise an xor operation in matlab -
i have run next code in profiler in matlab , quite essential me vectorise code sense unnecessary loop.
i have 2 matrices g , source_data. every column in g determine rows need pick source_data , xor them together.
i creating g , source_data using next piece of code
for i=1:10 source_data(i,:)=rand(1,20)<.8; end i=1:15 g(:,i)=rand(10,1)<.9; end
i performing xor operation using loop below:
z=1; while(i<=15) j=1:10 if(g(j,i)==1) intersum(z+1,:)=xor(intersum(z,:), source_data(j,:)); z=z+1; end end c(i,:)=intersum(z,:); i=i+1; end
is there way vectorise code ? time lag acceptable little matrix big matrices code quite in efficient.
thanks,
bhavya
assuming that:
i starts @ 1 intersum starts @ zeroshere's vectorized form of code produces exact same result original:
function c = version_a() source_data = rand(10,20)<.8; g = rand(10,15)<.9; intersum = zeros(1, size(source_data,2)); z = 1; = 1; while <= 15 j=1:10 if(g(j,i)==1) intersum(z+1,:)=xor(intersum(z,:), source_data(j,:)); z=z+1; end end c(i,:)=intersum(z,:); i=i+1; end ret = c; end function c = version_b() source_data = rand(10,20)<.8; % can initialize in single phone call g = rand(10,15)<.9; % same here c = zeros(size(g,2),size(source_data,2)); c(1,:) = mod(sum(source_data(g(:,1),:)),2); = 2:15 c(i,:) = mod(c(i-1,:) + sum(source_data(g(:,i),:)),2); end end
to check timing of both versions used test function:
function ret = xor_test() ret = 0; seed = 123456789; laps = 10000; tic = 1:laps randstream.getdefaultstream.reset(seed); = version_a(); end toc tic = 1:laps randstream.getdefaultstream.reset(seed); b = version_b(); end toc ret = ret + sum(sum(b ~= a)); end
and got next timings on machine:
elapsed time 13.537738 seconds. elapsed time 2.302747 seconds. ans = 0
now why changed way...
a xor
operation on array of logical
s pretty much checking parity of sum (treating true
values 1). furhtermore, intersum
beingness used accumulator, there's who's values ends in c
skip altogether. taking rows g(j,i)
1 can done logical indexing.
and finally, if don't proposed version, i'd recommend preallocating your c
, intersum
vectors (in case you're not doing already). has made lot of difference me in past.
matlab vectorization xor
Comments
Post a Comment