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?
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.
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.
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.
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.
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.
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