Reputation: 616
I use a function which take an Array{Int, 2} as an argument but it does not work when the array only contains 1 integer (as the array type is Array{Int, 1} in that case).
I know how to create an Array{Int, 2} with 2 or more integers:
S2 = [1 2] # S2 is an Array{Int, 2}
S3 = [1 2 3] # S3 is an Array{Int, 2}
but I don't know how to create an Array{Int, 2} with only 1 integer:
S1 = [1] # S1 is an Array{Int, 1}
Is it possible?
Upvotes: 0
Views: 155
Reputation: 69869
Use hcat
function, e.g.:
julia> hcat(1)
1×1 Array{Int64,2}:
1
This also works if you want to convert vector to a matrix:
julia> x = [1]
1-element Array{Int64,1}:
1
julia> hcat(x)
1×1 Array{Int64,2}:
1
EDIT: as an afterthought you can also do it like this:
julia> fill(10,1,1)
1×1 Array{Int64,2}:
10
it is more complex, but this way you can simply create an object of higher dimension e.g.:
julia> fill(10,1,1,1)
1×1×1 Array{Int64,3}:
[:, :, 1] =
10
EDIT 2: a general solution to put a new dimension of length 1
to any array in any place would be to use a comprehension:
julia> x = [1 2
3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> [x[i,k] for i in 1:size(x,1), j in 1:1, k in 1:size(x,2)]
2×1×2 Array{Int64,3}:
[:, :, 1] =
1
3
[:, :, 2] =
2
4
Upvotes: 2
Reputation: 10982
Another possibility is to use reshape
julia> S1 = [1]
1-element Array{Int64,1}:
1
julia> reshape(S1,1,1)
1×1 Array{Int64,2}:
1
Upvotes: 3