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 6 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
2 changes: 2 additions & 0 deletions stdlib/LinearAlgebra/src/LinearAlgebra.jl
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export
copyto!,
copy_transpose!,
cross,
cols,
arnavs marked this conversation as resolved.
Show resolved Hide resolved
adjoint,
adjoint!,
det,
Expand Down Expand Up @@ -123,6 +124,7 @@ export
opnorm,
rank,
rdiv!,
rows,
schur,
schur!,
svd,
Expand Down
38 changes: 38 additions & 0 deletions stdlib/LinearAlgebra/src/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1415,3 +1415,41 @@ function normalize(v::AbstractVector, p::Real = 2)
return T[]
end
end

# Iterator for the rows() and cols()
struct MatrixDimIterator{T}
arnavs marked this conversation as resolved.
Show resolved Hide resolved
row::Bool
length::Int
M::Matrix{T}
end

function Base.iterate(it::MatrixDimIterator, state = 1)
if state > it.length
return nothing
elseif it.row == true
obj = @view it.M[state, :]
arnavs marked this conversation as resolved.
Show resolved Hide resolved
return (obj, state+1)
else
obj = @view it.M[:, state]
return (obj, state+1)
end
end

Base.eltype(it::MatrixDimIterator) = it.row == true ? typeof(@view it.M[1, :]) : typeof(@view it.M[:, 1])
Base.length(it::MatrixDimIterator) = it.length
"""
rows(M::Matrix{T})

Get an iterator for the rows of M.
See also [`cols`](@ref).
"""
rows(M::Matrix) = MatrixDimIterator(true, size(M, 1), M)


"""
cols(M::Matrix{T})

Get a iterator for the columns of M.
See also [`rows`](@ref).
"""
cols(M::Matrix) = MatrixDimIterator(false, size(M, 2), M)
7 changes: 7 additions & 0 deletions stdlib/LinearAlgebra/test/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,13 @@ end
@test_throws ErrorException transpose(rand(2,2,2,2))
end


@testset "rows and columns tests" begin
M = [1 2 3; 4 5 6; 7 8 9]
@test collect(rows(M)) == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
@test collect(cols(M)) == [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
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