Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia - Increase the size of an array, inserting a value at the beginning

Tags:

arrays

julia

I have an array filled with some values. For example, after running the following code:

array = zeros(10)

for i in 1:10
   array[i] = 2*i + 1
end

the array looks like this:

10-element Array{Float64,1}:
  3.0
  5.0
  7.0
  9.0
 11.0
 13.0
 15.0
 17.0
 19.0

Now, I would like to add a new value in the first position to obtain something like this:

11-element Array{Float64,1}:
  1.0
  3.0
  5.0
  7.0
  9.0
 11.0
 13.0
 15.0
 17.0
 19.0

How to do that?

like image 766
Julien Avatar asked May 07 '18 11:05

Julien


People also ask

How do I add values to an array in Julia?

We can add elements to an array in Julia at the end, at the front and at the given index using push!() , pushfirst!() and splice!() functions respectively.

How do I get the size of an array in Julia?

Get array dimensions and size of a dimension in Julia – size() Method. The size() is an inbuilt function in julia which is used to return a tuple containing the dimensions of the specified array. This returned tuple format is (a, b, c) where a is the rows, b is the columns and c is the height of the array.

How do you reshape an array in Julia?

Reshaping array dimensions in Julia | Array reshape() Method The reshape() is an inbuilt function in julia which is used to return an array with the same data as the specified array, but with different specified dimension sizes.

How do you fill an array in Julia?

Create an array filled with the value x . For example, fill(1.0, (10,10)) returns a 10x10 array of floats, with each element initialized to 1.0 . If x is an object reference, all elements will refer to the same object. fill(Foo(), dims) will return an array filled with the result of evaluating Foo() once.


1 Answers

It looks like you want to use pushfirst!. This function modifies your array by inserting the new value(s) at the beginning:

julia> pushfirst!(array, 1)
11-element Array{Float64,1}:
  1.0
  3.0
  5.0
  7.0
  9.0
 11.0
 13.0
 15.0
 17.0
 19.0
 21.0

(N.B. in Julia 0.6 and earlier, pushfirst! is named unshift!.)

You may also be interested in insert!, which grows the collection by inserting a value at a specific index, and push! which add one or more values to the end of the collection.

See the Deques section of the documentation for many more useful functions for modifying collections.

like image 86
Alex Riley Avatar answered Oct 18 '22 13:10

Alex Riley