Iterate through rows/columns

1,360 views
Skip to first unread message

Spencer Russell

unread,
Feb 10, 2014, 9:18:25 PM2/10/14
to julia...@googlegroups.com
Often I'm using matrices as collections of vectors, for example each column of the matrix is a vector.

If I want to iterate through the vectors, I find myself doing:

for i in 1:size(mat, 2)
    # do stuff with mat[:, i]
end

Is there a way to treat the matrix as an iterable, something like

for v in cols(mat)
    # do stuff with v
end

or more generally

for v in slices(mat, 2)
    # do stuff with v
end

I could use mapslices with the do notation like

mapslices(mat, 2) do v
    # do stuff with v
end

but that creates an anon function, which I've heard is somewhat slow, is that still correct?

I'm just looking for feedback on what the most Julian thing to do here is, as I find I'm doing this quite a bit in my code.

-s

John Myles White

unread,
Feb 10, 2014, 9:35:52 PM2/10/14
to julia...@googlegroups.com
Personally, I always use your first option:

for i in 1:size(mat, 2)
# do stuff with mat[:, i]
end

-- John

Spencer Russell

unread,
Feb 10, 2014, 10:01:08 PM2/10/14
to julia...@googlegroups.com
Just realized the mapslices isn't really equivalent, as it assumes each iteration of the do block will return something. Perhaps there's something like an "iterslices"?

Trying to use a function that returns nothing in mapslices throws an error:

julia> m = [1 2 3; 4 5 6; 7 8 9; 10 11 12]'
3x4 Array{Int64,2}:
 1  4  7  10
 2  5  8  11
 3  6  9  12

julia> mapslices(m, 2) do v
           print(v)
       end
1
4
7
10
ERROR: no method size(Nothing)
 in mapslices at abstractarray.jl:1619
 in mapslices at abstractarray.jl:1590

Josh Langsfeld

unread,
Feb 10, 2016, 12:01:18 PM2/10/16
to julia-users, s...@mit.edu
Exactly two years later seems like a good-enough time to bring this back up. Has the situation changed here at all, maybe in a package? I've experimented a bit and the code for doing row and column iteration at least is absurdly simple. If multiple people would make use of it, where would be a good place to have it?

Kristoffer Carlsson

unread,
Feb 10, 2016, 12:23:20 PM2/10/16
to julia-users
There was a recent discussion here: https://github.com/JuliaLang/julia/issues/14491
Reply all
Reply to author
Forward
0 new messages