Given an array of arrays
x = [[1, 2, 3, 4], [4, 5, 6, 7]]
,
what is the clean & efficient way to truncate each of the inner arrays such that I end up with
[[1, 2], [4, 5]]
?
Is there anything as simple as x[:,1:2]
like for multidimensional arrays?
You can broadcast getindex
:
julia> x = [[1, 2, 3, 4], [5, 6, 7, 8]];
julia> getindex.(x, (1:2,))
2-element Array{Array{Int64,1},1}:
[1, 2]
[5, 6]
It seems to be a bit faster than using map
:
julia> foo(xs) = getindex.(xs, (1:2,))
foo (generic function with 1 method)
julia> bar(xs) = map(x -> x[1:2], xs)
bar (generic function with 1 method)
julia> @btime foo($([rand(1000) for _ in 1:1000]));
55.558 μs (1001 allocations: 101.69 KiB)
julia> @btime bar($([rand(1000) for _ in 1:1000]));
58.841 μs (1002 allocations: 101.70 KiB)
If you are ok with mutating the input vectors, then this is a very efficient way of doing it:
resize!.(x, 2)
This mutates x
in place, so you don't need to assign an output variable.
You can also use view
. That doesn't mutate the input, but neither does it allocate a new vector. It's faster than the broadcasted getindex
, but not as fast as resize!
:
xv = view.(x, Ref(1:2))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.