Extend B to 2D and then divide -
A/B[:,None].astype(float)
Sample run -
In [9]: A
Out[9]:
array([[ 2, 4],
[ 6, 8],
[10, 12]])
In [10]: B
Out[10]: array([1, 2, 4])
In [11]: A/B[:,None].astype(float)
Out[11]:
array([[ 2. , 4. ],
[ 3. , 4. ],
[ 2.5, 3. ]])
Or use from __future__ import division that takes care of division to result in a floating pt array -
In [14]: from __future__ import division
In [15]: A/B[:,None]
Out[15]:
array([[ 2. , 4. ],
[ 3. , 4. ],
[ 2.5, 3. ]])
Performance boost with multiplication by reciprocal -
In [32]: A = np.random.rand(300,200)
In [33]: B = np.random.rand(300)
In [34]: from __future__ import division
In [35]: %timeit A/B[:,None]
1000 loops, best of 3: 336 µs per loop
In [36]: %timeit A*(1.0/B[:,None])
10000 loops, best of 3: 101 µs per loop
More info on this could be found here. Also, one needs to be careful using this method though, if the values of B are extremely close to 0.
Do you really need to be able to handle both 1D and 2D inputs with the same function? If you know the input is going to be 1D, use
X[:, i] = x
If you know the input is going to be 2D, use
X[:, start:end] = x
If you don't know the input dimensions, I recommend switching between one line or the other with an if, though there might be some indexing trick I'm not aware of that would handle both identically.
Your x has shape (N,) rather than shape (N, 1) (or (1, N)) because numpy isn't built for just matrix math. ndarrays are n-dimensional; they support efficient, consistent vectorized operations for any non-negative number of dimensions (including 0). While this may occasionally make matrix operations a bit less concise (especially in the case of dot for matrix multiplication), it produces more generally applicable code for when your data is naturally 1-dimensional or 3-, 4-, or n-dimensional.
I think you have the answer already included in your question. Numpy allows the arrays be of any dimensionality (while afaik Matlab prefers two dimensions where possible), so you need to be correct with this (and always distinguish between (n,) and (n,1)). By giving one number as one of the indices (like 0 in 3rd row), you reduce the dimensionality by one. By giving a range as one of the indices (like 0:1 in 4th row), you don't reduce the dimensionality.
Line 3 makes perfect sense for me and I would assign to the 2-D array this way.