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

Row and Column Iterator for Matrices #29749

Merged
merged 25 commits into from
Dec 3, 2018
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions stdlib/LinearAlgebra/src/LinearAlgebra.jl
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ export
diagind,
diagm,
dot,
eachcol,
eachrow,
eachslice,
eigen,
eigen!,
eigmax,
Expand Down
27 changes: 27 additions & 0 deletions stdlib/LinearAlgebra/src/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1415,3 +1415,30 @@ function normalize(v::AbstractVector, p::Real = 2)
return T[]
end
end

"""
eachrow(A::AbstractVecOrMat)

Get a generator over views of A's first dimension.
arnavs marked this conversation as resolved.
Show resolved Hide resolved
See also [`eachcol`](@ref) and [`eachslice`](@ref).
"""
eachrow(A::AbstractVecOrMat) = (view(A, i, :) for i in axes(A, 1))


"""
eachcol(A::AbstractVecOrMat)

Get a generator over views of A's second dimension.
See also [`eachrow`](@ref) and [`eachslice`](@ref).
"""
eachcol(A::AbstractVecOrMat) = (view(A, :, i) for i in axes(A, 2))

"""
eachslice(A::AbstractArray, d)
arnavs marked this conversation as resolved.
Show resolved Hide resolved

Get an iterator over views of A's dth dimension. If
A has less than d dimensions, collect(eachslice(A, d))
will just return a trivial collection with a view into A.
See also [`eachrow`](@ref) and [`eachcol`](@ref).
"""
eachslice(A, dim) = (selectdim(A, dim, i) for i in axes(A, dim))
15 changes: 15 additions & 0 deletions stdlib/LinearAlgebra/test/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,21 @@ end
@test_throws ErrorException transpose(rand(2,2,2,2))
end


@testset "rows and columns tests" begin
# Simple ones
M = [1 2 3; 4 5 6; 7 8 9]
@test collect(eachrow(M)) == collect(eachslice(M, 1)) == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
@test collect(eachcol(M)) == collect(eachslice(M, 2)) == [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
@test collect(eachslice(M, 4))[1] == M

# Higher-dimensional case
M = reshape([(1:16)...], 2, 2, 2, 2)
@test_throws MethodError collect(eachrow(M))
@test_throws MethodError collect(eachcol(M))
@test collect(eachslice(M, 1))[1][:, :, 1] == [1 5; 3 7]
end

@testset "generic functions for checking whether matrices have banded structure" begin
using LinearAlgebra: isbanded
pentadiag = [1 2 3; 4 5 6; 7 8 9]
Expand Down