I need to pad zeros to specific locations in binary numbers. Looping the array form of a binary number such as dec2bin(43) and adding the zeros and adjusting th
Race begins! Mendo wins, gevang is a good second, thewaywewalk is the third and jaheruddin comes in fourth. The Shai's bitshifting is implemented in the shai function, unfortunately not yet getting it run faster.
Results
gevang :2.2e-05
thewaywewalk :5.6975e-05
mendo :2.2102e-05
jaheruddin :0.0001693
shai (poor hhh-implementation) 5.3288e-04
Warmed-up testing of the answers
function test_padding_zeros()
function myOutput=gevang(xx,positions)
nPads = length(positions);
nPadsShifts = 1:nPads;
myOutput = ones(1, length(xx) + nPads); % re-indexing on the new array
myOutput(positions + nPadsShifts) = 0; % padding values
myOutput(myOutput==1) = xx; % set original bit values
end
function myOutput=thewaywewalk(x,positions)
idx = numel(x):-1:1;
myOutput = num2cell(x);
myOutput(2,idx(positions)) = {0};
myOutput = [myOutput{:}];
end
function myOutput=jaheruddin(myInput,positions) % myInput can be a row vector or a matrix!
n = size(myInput,2)+numel(positions);
myOutput = false(size(myInput,1),n);
myOutput(:,setxor((1:length(positions)),1:n))=myInput;
end
function myOutput=mendo(myInput,positions)
myOutput = ones(1,length(myInput)+length(positions));
myOutput(positions+(1:length(positions))) = 0;
myOutput(myOutput==1) = myInput;
end
function out = bizarreBitShift( bNum, fromBit, shiftAmount )
% construct a mask
msk = uint32( (2^( fromBit - 1 ) )-1 );
shiftPart = bitand( uint32(bNum), bitcmp(msk) ); % bitcmp - complement of bits
staticPart = bitand( uint32(bNum), msk );
out = bitshift( shiftPart , shiftAmount );
out = bitor( out, staticPart );
end
function myOutput=shai(myInput,positions)
shiftAmount=1;
myOutput=sprintf('%d',myInput);
myOutput=bin2dec(myOutput);
k=0;
for ii=1:length(positions)
fromBit=positions(ii)+k;
myOutput=bizarreBitShift(myOutput, fromBit, shiftAmount);
k=k+1;
end
myOutput=ismember(dec2bin(myOutput),'1');
end
positions = [1 3 6]; %// example data
myInput = [1 0 1 0 1 1]; %// example data
ggevang=@() gevang(myInput,positions);
tthewaywewalk=@() thewaywewalk(myInput,positions);
mmendo=@() mendo(myInput,positions);
jjaheruddin=@() jaheruddin(myInput,positions);
sshai=@() shai(myInput,positions);
timeit(ggevang)
timeit(tthewaywewalk)
timeit(mmendo)
timeit(jjaheruddin)
timeit(sshai)
end