Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Norm along side axis #697

Open
DPDmancul opened this issue Feb 20, 2020 · 3 comments
Open

Norm along side axis #697

DPDmancul opened this issue Feb 20, 2020 · 3 comments

Comments

@DPDmancul
Copy link

DPDmancul commented Feb 20, 2020

It would be nice if the LinearAlgebra.norm function have the dims keyword, like others linear algebra functions and like numpy norm axis parameter (https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html)

Just for example:

function norm(itr, p::Real=2; dims)
    sum(itr.^p; dims=dims).^(1/p)
end
@andreasnoack
Copy link
Member

I think we are generally moving towards delegating these kinds of computations to mapslices or https://github.com/bramtayl/JuliennedArrays.jl

@dkarrasch
Copy link
Member

Ignoring the "wrong" orientation of the resulting array, doing it via eachslice seems way faster:

using LinearAlgebra, BenchmarkTools
A = rand(100, 100);
@btime map(norm, eachslice($A, dims=2));  #  5.689 μs (105 allocations: 5.64 KiB)
@btime mapslices(norm, $A, dims=1);  #  61.642 μs (838 allocations: 24.02 KiB)

(The two compute the same despite the different dims, see JuliaLang/julia#34840.)

@mcabbott
Copy link
Collaborator

mcabbott commented Feb 23, 2020

The eachslice version is still a lot slower than working on one big array:

function norm2(A; dims)
    B = sum(x -> x^2, A; dims=dims)
    B .= sqrt.(B)
end
@btime norm2($A, dims=1); # 1.786 μs (1 allocation: 896 bytes)

Even if calling map(norm, eachslice) ends up being the preferred interface, it seems worthwhile to have some implementation like this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants