Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add vectors to the columns of some array in Julia?

I know that, with package DataFrames, it is possible by doing simply

julia> df = DataFrame();

julia> for i in 1:3
          df[i] = [i, i+1, i*2]
       end

julia> df
3x3 DataFrame
|-------|----|----|----|
| Row # | x1 | x2 | x3 |
| 1     | 1  | 2  | 3  |
| 2     | 2  | 3  | 4  |
| 3     | 2  | 4  | 6  |

... but are there any means to do the same on an empty Array{Int64,2} ?

like image 633
kaslusimoes Avatar asked May 23 '14 22:05

kaslusimoes


People also ask

How do you add vectors in Julia?

A Vector in Julia can be created with the use of a pre-defined keyword Vector() or by simply writing Vector elements within square brackets([]). There are different ways of creating Vector. vector_name = [value1, value2, value3,..] or vector_name = Vector{Datatype}([value1, value2, value3,..])

How do I add elements to an array in Julia?

Julia allows adding new elements in an array with the use of push! command. Elements in an array can also be added at a specific index by passing the range of index values in the splice!

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

If you know how many rows you have in your final Array, you can do it using hcat:

# The number of lines of your final array
numrows = 3

# Create an empty array of the same type that you want, with 3 rows and 0 columns:
a = Array(Int, numrows, 0)

# Concatenate 3x1 arrays in your empty array:
for i in 1:numrows
    b = [i, i+1, i*2] # Create the array you want to concatenate with a
    a = hcat(a, b)
end

Notice that, here you know that the arrays b have elements of the type Int. Therefore we can create the array a that have elements of the same type.

like image 187
prcastro Avatar answered Sep 21 '22 19:09

prcastro