Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an additional dimension to an array

Tags:

julia

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

like image 884
Wolf Avatar asked Oct 03 '19 10:10

Wolf


People also ask

How do you add a dimension?

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.

Can you add arrays with different dimensions?

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.

How do you expand an array in NP?

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.

How do you add an element to an array of an element?

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.


2 Answers

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
like image 183
Bogumił Kamiński Avatar answered Sep 28 '22 17:09

Bogumił Kamiński


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.

like image 41
Wolf Avatar answered Sep 28 '22 16:09

Wolf