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

Christopher Barker Chris.Barker@noaa....
Fri Dec 28 11:00:56 CST 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?


#!/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()


for i in range(numrows):
     for j in range(numcols):

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.

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


More information about the Numpy-discussion mailing list