Note: This question/answer is copied from the Julia Slack channel.
If I have an arbitrary Julia Array
, how can I add another dimension.
julia> a = [1, 2, 3, 4]
4-element Array{Int64,1}:
1
2
3
4
The desired output would be e.g.:
julia> a[some_magic, :]
1×4 Array{Int64,2}:
1 2 3 4
Or:
julia> a[:, some_magic]
4×1 Array{Int64,2}:
1
2
3
4
To create a new dimension. In Solution Explorer, right-click Dimensions, and then click New Dimension. On the Select Creation Method page of the Dimension Wizard, select Use an existing table, and then click Next. You might occasionally have to create a dimension without using an existing table.
Ahh your array_2 only has one dimension, needs to have same number of dimensions with your array_1 . You can either reshape it array_2. reshape(-1,1) , or add a new axis array_2[:,np. newaxis] to make it 2 dimensional before concatenation.
To expand the shape of an array, use the numpy. expand_dims() method. Insert a new axis that will appear at the axis position in the expanded array shape. The function returns the View of the input array with the number of dimensions increased.
For adding an element to the array, First, you can convert array to ArrayList using 'asList ()' method of ArrayList. Add an element to the ArrayList using the 'add' method. Convert the ArrayList back to the array using the 'toArray()' method.
A less tricky thing I usually do to achieve this is:
julia> reshape(a, 1, :)
1×4 Array{Int64,2}:
1 2 3 4
julia> reshape(a, :, 1)
4×1 Array{Int64,2}:
1
2
3
4
(it also seems to involve less typing)
Finally a common case requiring transforming a vector to a column matrix can be done:
julia> hcat(a)
4×1 Array{Int64,2}:
1
2
3
4
EDIT also if you add trailing dimensions you can simply use :
:
julia> a = [1,2,3,4]
4-element Array{Int64,1}:
1
2
3
4
julia> a[:,:]
4×1 Array{Int64,2}:
1
2
3
4
julia> a[:,:,:]
4×1×1 Array{Int64,3}:
[:, :, 1] =
1
2
3
4
The trick is so use [CartesianIndex()]
to create the additional axes:
julia> a[[CartesianIndex()], :]
1×4 Array{Int64,2}:
1 2 3 4
And:
julia> a[:, [CartesianIndex()]]
4×1 Array{Int64,2}:
1
2
3
4
If you want to get closer to numpy's syntax, you can define:
const newaxis = [CartesianIndex()]
And just use newaxis
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With