I am a Matlab user, and trying to move into Python. I tried to code a minimal example of de2bi function (which converts a decimal into binary as right-msb) in Python which I had before in Matlab. But, I am confused with numpy arrays.
Python code:
import numpy as np
def de2bi(d, n)
d = np.array(d)
power = 2**np.arange(n)
d = d * np.ones((1,n))
b = np.floor((d%(2*power))/power)
return b
Python output:
>>> print(de2bi(13,8))
[[ 1. 0. 1. 1. 0. 0. 0. 0.]]
print(de2bi([13,15],8)) #This line fails
Matlab code:
function b = d2b( d, n )
d = d(:);
power = ones(length(d), 1)*(2.^(0 : n-1));
d = d * ones(1, n);
b = floor(rem(d, 2*power)./power);
end
Matlab output:
>> d2b(13,8)
ans =
1 0 1 1 0 0 0 0
>> d2b([13,15],8)
ans =
1 0 1 1 0 0 0 0
1 1 1 1 0 0 0 0
Matlab code is working both for integer inputs and array of integers. But python code works for integer inputs, but keeps failing for arrays. How to manage operations both for integers and integer arrays in Python automatically? It may be a very easy question, excuse me, but I am a very newbie in python.
Thanks in advance.
flipudlooks funny. You should be able write the numpy power line much like matlab one, taking advantage of broadcasting to produce a 2d array.