Raoul
Raoul

Reputation: 1892

Python equivalent for Matlab vector slice

I have the following code in Matlab (I do not have Matlab), that apparently constructs integers by sampling sequences of binary values:

velocity_LUT_10bit = zeros(2^10,1);
for n = 1:length(velocity_LUT_10bit),
    imagAC = bin2dec(num2str(bitget(n-1,9:-1:6))) - bitget(n-1,10)*2^4;       % Imaginary part of autocorrelation: signed 5-bit integer
    realAC = bin2dec(num2str(bitget(n-1,4:-1:1))) - bitget(n-1, 5)*2^4;       % Real part of autocorrelation: signed 5-bit integer
    velocity_LUT_10bit(n) = velNyq_CF*angle((realAC+0.5)/16 + 1i*(imagAC+0.5)/16)/pi;
end;

I am having trouble understanding the bitget() function. From the docs, the first arg is the sampled sequence, while the second arg specifies the range of the sample, but I am confused about what the slicing x:-y:z means. I understand it from the docs as "sample from index x to z, going right to left by strides of y". Is that correct?

What would be the numpy equivalent of bin2dec(num2str(bitget(n-1,9:-1:6)))? I understood I should be using numpy.packbits(), but I am a bit stuck.

Upvotes: 0

Views: 585

Answers (1)

hpaulj
hpaulj

Reputation: 231385

In an Octave session:

>> for n=0:3:15,
   bitget(n,1:1:5)
end
ans =
   0   0   0   0   0
ans =
   1   1   0   0   0
ans =
   0   1   1   0   0
ans =
   1   0   0   1   0
ans =
   0   0   1   1   0
ans =
   1   1   1   1   0

This is just the binary representation of the number, with a sliced selection of the bits. Octave/Matlab is using the 'start:step:stop' syntax.

The rest converts the numbers to a string and from binary to decimal:

>> num2str(bitget(13,5:-1:1))
ans = 0  1  1  0  1
>> bin2dec(num2str(bitget(13,5:-1:1)))
ans =  13

bitget(n-1,9:-1:6) must be fetching the 9th to 6th bits (powers of 2) in reverse order. So for a number up to 2^10-1, it's pulling out 'bits' 1-4, 5, 6-9, and 10.


I'm not familiar with Python/numpy binary representations, but here's a start:

>> num2str(bitget(100,10:-1:1))
ans = 0  0  0  1  1  0  0  1  0  0
In [434]: np.binary_repr(100,10)
Out[434]: '0001100100'

Upvotes: 1

Related Questions