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} $$
A = np.array([1,2,3,4]).reshape(1,4)
b = 100
C = A + b
print(C)
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} $$
A = np.array([1,2,3,4]).reshape(4,1)
b = 100
C = A + b
print(C)
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} $$
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)
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} $$
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)
Notice that we have used .reshape() funcion among all previous examples. That was the way to avoid "ranak 1 arrays".
A = np.array([1,2,3,4])
A.shape
print(A)
print(A.T)
print(np.dot(A, A))
print(np.dot(A, A.T))
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.
A = A.reshape(1,4)
A.shape
We can also use an assert statement.
assert( A.shape == (1,4))
print('Dimension of matrix A is 1 by 4')