Ask Your Question
2

How do I normalize the columns of a matrix?

asked 2018-06-13 00:39:51 +0100

ionsme gravatar image

How do I normalize the columns of a matrix?

such as $A = matrix(5,5,[\text{some numbers}])$

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2018-06-13 03:35:59 +0100

slelievre gravatar image

The simplest way to normalize the column of a matrix is probably to replace each column of a matrix by itself divided by its norm.

Create a matrix:

sage: a = matrix(RDF, 4, [randint(-10, 10) for _ in range(16)])
sage: a
[-2.0  6.0 -6.0 -2.0]
[ 6.0  1.0 -8.0  4.0]
[-7.0  4.0 -3.0  9.0]
[ 6.0 -9.0  9.0 -5.0]

Normalize each column:

sage: for j in range(a.ncols()):
....:     v = a.column(j)
....:     a[:,j] = v/v.norm()
....:

Show the result:

sage: a
[-0.17888543819998318   0.5183210553488161   -0.435285750066007  -0.1781741612749496]
[  0.5366563145999496  0.08638684255813601  -0.5803810000880093   0.3563483225498992]
[ -0.6260990336999411  0.34554737023254406  -0.2176428750330035   0.8017837257372732]
[  0.5366563145999496  -0.7774815830232241   0.6529286250990105 -0.44543540318737396]

Check the norms of the new columns:

sage: [c.norm() for c in a.columns()]
[1.0, 1.0, 1.0, 1.0]
edit flag offensive delete link more

Comments

carefully,I would add an if ?:

for j in range(a.ncols()):
    v = a.column(j)
    if v.norm() <> 0 :
        a[:,j] = v/v.norm()
ortollj gravatar imageortollj ( 2019-11-10 09:47:36 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2018-06-13 00:39:51 +0100

Seen: 5,052 times

Last updated: Jun 13 '18