logo

How to Normalize Matrices Column-wise in Julia 📂Julia

How to Normalize Matrices Column-wise in Julia

Overview

This document introduces a tip for easily normalizing matrices in Julia 1. At its core, it’s just mixing the method of scalar multiplying matrices by rows and columns, the eachcol() function, and the norm() function from the LinearAlgebra module, but it’s concise, ending in one line, and proving to be quite useful to memorize for frequent use.

Code

julia> using LinearAlgebra

julia> X =  reshape(1:15, 5, :)
5×3 reshape(::UnitRange{Int64}, 5, 3) with eltype Int64:
 1   6  11
 2   7  12
 3   8  13
 4   9  14
 5  10  15

Given a matrix X, normalizing it by columns can be succinctly done with just one line: X ./ norm.(eachcol(X))'. The execution and the results confirming that it was indeed properly normalized are as follows.

julia> Z = X ./ norm.(eachcol(X))'
5×3 Matrix{Float64}:
 0.13484  0.330289  0.376192
 0.26968  0.385337  0.410391
 0.40452  0.440386  0.444591
 0.53936  0.495434  0.47879
 0.6742   0.550482  0.512989

julia> norm.(eachcol(Z))
3-element Vector{Float64}:
 1.0
 1.0
 1.0

Complete Code

using LinearAlgebra

X =  reshape(1:15, 5, :)
Z = X ./ norm.(eachcol(X))'
norm.(eachcol(Z))

Environment

  • OS: Windows
  • julia: v1.9.0