[Numpy-discussion] any better way to normalize a matrix

Christopher Barker Chris.Barker at noaa.gov
Fri Dec 28 12:00:56 EST 2007


Anne had it right -- much of the point of numpy is to use nd-arrays as 
the powerful objects they are - not just containers. Below is  a version 
of your code for comparison.

Note to numpy devs:

I like the array methods a lot -- is there any particular reason there 
is no ndarray.abs(), or has it just not been added?

-Chris



#!/usr/bin/env python

"""
Simple exmaple of normalizing an array
"""

import numpy as N
from numpy import random


mymatrix=random.uniform(-100, 100,(3,4))

print "before:", mymatrix
mymatrix2 = mymatrix.copy()

numrows,numcols=mymatrix.shape

for i in range(numrows):
     temp=mymatrix[i].max()
     for j in range(numcols):
         mymatrix[i,j]=abs(mymatrix[i,j]/temp)

print "old way:", mymatrix

## "vectorized" way:

# the "reshape" is a bit awkward, but it makes the 1-d result the right 
shape to "broadcast" to the original array
row_max = mymatrix2.max(axis=1).reshape((-1, 1))

print row_max
mymatrix2 = N.absolute((mymatrix2 / row_max))

print "vectorized:", mymatrix2
if (mymatrix == mymatrix2).all():
     print "They are the same"


-- 
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov



More information about the NumPy-Discussion mailing list