Trobeu una matriu o una norma vectorial utilitzant NumPy

Per trobar una norma matricial o vectorial utilitzem la funció numpy.linalg.norm() de la biblioteca de Python Numpy. Aquesta funció retorna una de les set normes matricials o una de les normes vectorials infinites depenent del valor dels seus paràmetres.

Sintaxi: numpy.linalg.norm(x, ord=Cap, axis=Cap)
Paràmetres:
x: entrada
paraula: ordre de la norma
eix: Cap, retorna un vector o una norma matricial i si és un valor enter, especifica l'eix de x al llarg del qual es calcularà la norma vectorial

Exemple 1:

Python 3




# import library> import> numpy as np> # initialize vector> vec> => np.arange(> 10> )> # compute norm of vector> vec_norm> => np.linalg.norm(vec)> print> (> 'Vector norm:'> )> print> (vec_norm)>

Sortida:

Vector norm: 16.881943016134134 

El codi anterior calcula la norma vectorial d'un vector de dimensió (1, 10)
Exemple 2:

Python 3




# import library> import> numpy as np> # initialize matrix> mat> => np.array([[> 1> ,> 2> ,> 3> ],> > [> 4> ,> 5> ,> 6> ]])> # compute norm of matrix> mat_norm> => np.linalg.norm(mat)> print> (> 'Matrix norm:'> )> print> (mat_norm)>

Sortida:

Matrix norm: 9.539392014169456 

Aquí, obtenim la norma matricial per a una matriu de dimensió (2, 3)
Exemple 3:
Per calcular la norma matricial al llarg d'un eix particular:

Python 3




# import library> import> numpy as np> mat> => np.array([[> 1> ,> 2> ,> 3> ],> > [> 4> ,> 5> ,> 6> ]])> # compute matrix num along axis> mat_norm> => np.linalg.norm(mat, axis> => 1> )> print> (> 'Matrix norm along particular axis :'> )> print> (mat_norm)>

Sortida:

Matrix norm along particular axis : [3.74165739 8.77496439] 

Aquest codi genera una norma matricial i la sortida també és una matriu de forma (1, 2)
Exemple 4:

Python 3




# import library> import> numpy as np> # initialize vector> vec> => np.arange(> 9> )> # convert vector into matrix> mat> => vec.reshape((> 3> ,> 3> ))> # compute norm of vector> vec_norm> => np.linalg.norm(vec)> print> (> 'Vector norm:'> )> print> (vec_norm)> # computer norm of matrix> mat_norm> => np.linalg.norm(mat)> print> (> 'Matrix norm:'> )> print> (mat_norm)>

Sortida:

Vector norm: 14.2828568570857 Matrix norm: 14.2828568570857 

A partir de la sortida anterior, queda clar si convertim un vector en una matriu, o si tots dos tenen els mateixos elements, la seva norma també serà igual.