Dear julia community, I am a beginner in julia can you please explain to me why I am facing the following problems…?
1.
#code
a = [1 2 3; 4 5 6]
map(x -> println(a), [1,2])
#output in notebook
[1 2 3; 4 5 6]
[1 2 3; 4 5 6]
2-element Vector{Nothing}:
nothing
nothing
#output in REPL
[1 2 3; 4 5 6]
[1 2 3; 4 5 6]
Why are my outputs different…?
- I want shuffle matrix “a” along the rows
#code
map!(x -> shuffle!(a[x,:]), [1,2]) |> println
println(a)
# output
[[3, 2, 1], [5, 4, 6]]
[1 2 3; 4 5 6]
can someone please explain my mistake…?
-
#Shuffling only one row
shuffle!(a[1,:])
println(a)
shuffle!(view(a[1,:]))
println(a)
#output
[1 2 3; 4 5 6]
BoundsError: attempt to access 3-element Vector{Int64} at index []
Stacktrace:
[1] throw_boundserror(A::Vector{Int64}, I::Tuple{})
@ Base .\abstractarray.jl:703
[2] checkbounds
@ .\abstractarray.jl:668 [inlined]
[3] view(::Vector{Int64})
@ Base .\subarray.jl:177
[4] top-level scope
@ c:\VSP.ipynb:3
- The output in the REPL is the same:
julia> map(x -> println(a), [1,2])
[1 2 3; 4 5 6]
[1 2 3; 4 5 6]
2-element Vector{Nothing}:
nothing
nothing
map(f, x)
means: for each item in x
, do f(x)
. Since in your example x
is [1, 2]
you’re doing:
for the number 1, println(a)
, then for the number 2 println(a)
. Since println
returns nothing
, you get [nothing, nothing]
at the end.
2./3. The main thing that’s happening here is that a[x, :]
creates a new Vector. So if you shuffle that vector, that won’t shuffle a
, because they’re no longer related to each other. It also means you can’t do view(a[1, :])
. You can do view(a, 1, :)
or @view a[1, :]
Using a proper view, I can shuffle the first row:
julia> shuffle!(@view a[1,:])
3-element view(::Matrix{Int64}, 1, :) with eltype Int64:
3
2
1
julia> a
2×3 Matrix{Int64}:
3 2 1
4 5 6
One way to shuffle all the rows is to use eachrow
, which creates an iterators of view
s
julia> a = [1 2 3; 4 5 6; 7 8 9];
julia> shuffle!.(eachrow(a));
julia> a
3×3 Matrix{Int64}:
1 3 2
5 4 6
7 9 8
If you dont want the outputs in an array, replace map
with foreach
, or use a for
loop.
Thank you @tomerarnon for your response
Thank you @gustaphe for your response