Difference between Numpy array and Numpy Matrix
Matrix is 2-dimensional while ndarray can be multi-dimensional
Example 1:
Here, we can print all the dimensions of an array in np.array.
Python3
import numpy as np arr1 = np.array([ 1 , 2 , 3 ]) print ( "1D array\n" , arr1) print ( "\n" ) arr2 = np.array([[ 1 , 2 ], [ 3 , 4 ]]) print ( "2D array\n" , arr2) print ( "\n" ) C = np.array([[[ 1 , 2 ], [ 3 , 4 ]], [[ 5 , 6 ], [ 7 , 8 ]], [[ 9 , 10 ], [ 11 , 12 ]]]) print ( "3D array\n" , C) |
Output:
1D array [1 2 3] 2D array [[1 2] [3 4]] 3D array [[[ 1 2] [ 3 4]] [[ 5 6] [ 7 8]] [[ 9 10] [11 12]]]
Example 2:
Matrix works normally for a 2D matrix and if a 1D matrix will convert into 2D Matrix, but if we pass a 3D matrix it will through an error.
Python3
import numpy as np arr1 = np.matrix([ 1 , 2 , 3 ]) print (arr1) print ( "Dimensions:" , arr1.ndim) print ( "\n" ) arr2 = np.matrix([[[ 1 , 2 ], [ 3 , 4 ]], [[ 5 , 6 ], [ 7 , 8 ]], [[ 9 , 10 ], [ 11 , 12 ]]]) print ( "2D array\n" , arr2) |
Output:
Different functionality of * operator in ndarray and Matrix
Example 1:
Array * operator does simple multiplication.
Python3
a = np.array([[ 1 , 2 ], [ 3 , 4 ]]) b = np.array([[ 1 , 2 ], [ 3 , 4 ]]) print ( "Array multiplication: \n" , a * b) |
Output:
Array multiplication: [[ 1 4] [ 9 16]]
Example 2:
While it does matrix multiplication.
Python3
a = np.matrix([[ 1 , 2 ], [ 3 , 4 ]]) b = np.matrix([[ 1 , 2 ], [ 3 , 4 ]]) print ( "Matrix multiplication: \n" , a * b) |
Output:
Matrix multiplication: [[ 7 10] [15 22]]
Matrix has an array.I for inverse, but ndarray has linalg.inv
Example 1:
The inverse can be done with array.I in ndarray.
Python3
arr1 = np.matrix([[ 1 , 2 ], [ 3 , 4 ]]) print ( 'Inverse \n' , arr1.I) |
Output:
Inverse [[-2. 1. ] [ 1.5 -0.5]]
Example 2:
The inverse can be done with np.linalg.inv in matrix.
Python3
b = np.array([[ 1 , 2 ], [ 3 , 4 ]]) print ( 'Inverse \n' , np.linalg.inv(b)) |
Output:
Inverse [[-2. 1. ] [ 1.5 -0.5]]
Difference between Numpy array and Numpy matrix
While working with Python many times we come across the question that what exactly is the difference between a numpy array and numpy matrix, in this article we are going to read about the same.
Contact Us