4aHxKzD
November 2, 2019, 12:22pm
1
Is there a quick way to create an 3x1 Array{ T , 2}
where T is a type ?
[A, B, C, ...]
or [A; B; C; ...]
construct a 1-d array (vector).
[A B C ...]
constructs a 2-d row array.
What about a 2-d column array? Does anyone know why [A; B; C; ...]
wasn’t chosen for this task?
See this discussion for multiple suggestions (depending on whether you want to construct from existing contents, etc):
Hey guys, I want to make an array with only a single column, so ie. something like 4x1 Array{Int32,1}
Whenever I use zeros or undef I get like this:
zeros(Int32,4,1)
4×1 Array{Int32,2}:
0
0
0
0
Can I force the output to be a single array? Please note I know that it is possible to do:
zeros(Int32,(4,))
4-element Array{Int32,1}:
0
0
0
0
But I cannot use this notation since I am reading some data and depending on the datatype it might have 3 or 1 columns, but I do not know number of el…
2 Likes
I guess reshape
is the way to go, but intuitively I think [A; B; C]
makes a lot of sense and would also remove the issue of two different syntaxes doing the same thing.
DNF
November 3, 2019, 4:43pm
4
[A, B]
and [A; B]
don’t do the same thing, though:
julia> A = [1, 2, 3]; B = [4, 5];
julia> [A, B]
2-element Array{Array{Int64,1},1}:
[1, 2, 3]
[4, 5]
julia> [A; B]
5-element Array{Int64,1}:
1
2
3
4
5
2 Likes
Didn’t think about that, thanks.
I think that the cheapest solution, with the same cost as creating a vector, is hvcat
:
julia> using BenchmarkTools
julia> @btime [1,2,3]
34.418 ns (1 allocation: 112 bytes)
3-element Array{Int64,1}:
1
2
3
julia> @btime reshape([1,2,3],:,1)
101.557 ns (3 allocations: 208 bytes)
3×1 Array{Int64,2}:
1
2
3
julia> @btime hvcat(1, 1,2,3)
46.672 ns (1 allocation: 112 bytes)
3×1 Array{Int64,2}:
1
2
3
It may be a bit annoying having to put that 1
as first argument, but easy to work around it, wrapping it in another function, e.g.
columnmatrix(args...) = hvcat(1, args...)
3 Likes
Julia 1.7 allows
julia> [1; 2; 3; 4 ;;]
4×1 Matrix{Int64}:
1
2
3
4
1 Like