Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to normalize the columns of a matrix in Julia

Given a matrix A of dimensions m,n, how would one normalize the columns of that matrix by some function or other process in Julia (the goal would be to normalize the columns of A so that our new matrix has columns of length 1)?

like image 489
Evan E Avatar asked Sep 11 '25 07:09

Evan E


1 Answers

mapslices seems to have some issues with performance. On my computer (and v1.7.2) this is 20x faster:

x ./ norm.(eachcol(x))'

This is an in-place version (because eachcol creates views), which is faster still (but still allocates a bit):

normalize!.(eachcol(x))

And, finally, some loop versions that are 40-70x faster than mapslices for the 5x3 matrix:

# works in-place:
function normcol!(x)
    for col in eachcol(x)
        col ./= norm(col)
    end
    return x
end
# creates new array:
normcol(x) = normcol!(copy(x))

Edit: Added a one-liner with zero allocations:

foreach(normalize!, eachcol(x))

The reason this does not allocate anything, unlike normalize!., is that foreach doesn't return anything, which makes it useful in cases where output is not needed.

like image 154
DNF Avatar answered Sep 14 '25 00:09

DNF