Column wise broadcast for a matrix

Sorry if this has been posted a bunch but my googling has failed me. How do I broadcast a function by column for a 2 dimensional matrix? Say I want to, for each column in a matrix, normalize it with respect to the mean of that column. normalize.(mymatrix) will apply to each element, not each column.

3 Likes

I think the most elegant way to broadcast a function by column is to use mapslices. So try this:

mapslices(normalize, mymatrix, 1)

The third argument specifies the dimensions to broadcast over. So 1 for columns, 2 for rows, or a vector for high level multidimensional magic. See the documentation for more info.

9 Likes

Thank you! exactly what I was looking for.

For more complicated things, one can use the do syntax I guess.

mapslices(mymatrix, 1) do x
x/norm(x)
end
2 Likes