In [1]:
import numpy as np

Adding a scalar to a row vector : $$A =  \begin{bmatrix} 1 & 2 & 3 & 4 \end{bmatrix} + 100 \iff \begin{bmatrix} 1 & 2 & 3 & 4 \end{bmatrix} + \begin{bmatrix} 100 & 100 & 100 & 100 \end{bmatrix} $$

In [2]:
A = np.array([1,2,3,4]).reshape(1,4)
b = 100
C = A + b
print(C)
[[101 102 103 104]]

Adding a scalar to a column vector : $$A =  \begin{bmatrix} 1 \\ 2 \\ 3 \\ 4 \end{bmatrix} + 100 \iff \begin{bmatrix} 1 \\ 2 \\ 3 \\ 4 \end{bmatrix} + \begin{bmatrix} 100 \\ 100 \\ 100 \\ 100 \end{bmatrix} $$

In [3]:
A = np.array([1,2,3,4]).reshape(4,1)
b = 100
C = A + b
print(C)
[[101]
 [102]
 [103]
 [104]]

Adding a row vector to a matrix: $$A =  \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{bmatrix} + \begin{bmatrix} 100 & 200 & 300 \end{bmatrix} \iff \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{bmatrix} + \begin{bmatrix} 100 & 200 & 300 \\ 100 & 200 & 300 \end{bmatrix} $$

In [4]:
A = np.array([[1,2,3],[4,5,6]])
B = np.array([100, 200, 300]).reshape(1,3)
print('Shape of A: ', A.shape)
print('Shape of B: ', B.shape)
C = A + B
print(C)
Shape of A:  (2, 3)
Shape of B:  (1, 3)
[[101 202 303]
 [104 205 306]]

Adding a column vector to a matrix: $$A =  \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{bmatrix} + \begin{bmatrix} 100 \\ 200 \end{bmatrix} \iff \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{bmatrix} + \begin{bmatrix} 100 & 100 & 100 \\ 200 & 200 & 200 \end{bmatrix} $$

In [5]:
A = np.array([[1,2,3], [4,5,6]])
B = np.array([100, 200]).reshape(2,1)
print('Shape of A: ', A.shape)
print('Shape of B: ', B.shape)
C = A + B
print(C)
Shape of A:  (2, 3)
Shape of B:  (2, 1)
[[101 102 103]
 [204 205 206]]

Notice that we have used .reshape() funcion among all previous examples. That was the way to avoid "ranak 1 arrays".

In [6]:
A = np.array([1,2,3,4])
A.shape
Out[6]:
(4,)
In [7]:
print(A)
print(A.T)
[1 2 3 4]
[1 2 3 4]
In [8]:
print(np.dot(A, A))
print(np.dot(A, A.T))
30
30

It doesn't behave consistently as neither a row vector nor a column vector, which makes some of its effects nonintuitive. So it isn't recommended to use it. Using reshape() function can solve this problem.

In [9]:
A = A.reshape(1,4)
A.shape
Out[9]:
(1, 4)

We can also use an assert statement.

In [10]:
assert( A.shape == (1,4))
print('Dimension of matrix A is 1 by 4')
Dimension of matrix A is 1 by 4