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)?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With