As a service to export from a nice discussion (Not by me) in Slack.
I need to take a large matrix and subtract the mean columnwise and inplace. Is there a fast way to do this?
By columnwise I mean taking the mean of the column and subtracting it.
Answer by @Oscar_Smith:
for i in axes(A,2)
@views A[:,i] .-= mean(A[:,i])
end
By @mcabbott
Or just
A .-= mean(A, dims=1)
The loop is faster for large arrays.
Note that it is equivalent to A[:,i] .= A[:,i] .- mean(A[:,i])
. Without @views
, both of the slices on the right would allocate.