How to add vectors to the columns of some array in

2019-02-23 14:34发布

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

3条回答
在下西门庆
2楼-- · 2019-02-23 15:05

Loop over the rows of the matrix:

A = zeros(3,3)
for i = 1:3
  A[i,:] = [i, i+1, 2i]
end
查看更多
甜甜的少女心
3楼-- · 2019-02-23 15:06

If at all possible, it is best to create your Array with the desired number of columns from the start. That way, you can just fill in those column values. Solutions using procedures like hcat() will suffer from inefficiency, since they require re-creating the Array each time.

If you do need to add columns to an already existing Array, you will be better off if you can add them all at once, rather than in a loop with hcat(). E.g. if you start with:

n = 10; m = 5;
A = rand(n,m);

then

A = [A rand(n, 3)]

will be faster and more memory efficient than:

for idx = 1:3
    A = hcat(A, rand(n))
end

E.g. compare the difference in speed and memory allocations between these two:

n = 10^5; m = 10;
A = rand(n,m);
n_newcol = 10;

function t1(A::Array, n_newcol)
    n = size(A,1)
    for idx = 1:n_newcol
        A = hcat(A, zeros(n))
    end
    return A
end

function t2(A::Array, n_newcol)
    n = size(A,1)
    [A zeros(n, n_newcol)]
end

# Stats after running each function once to compile
@time r1 = t1(A, n_newcol);  ## 0.145138 seconds (124 allocations: 125.888 MB, 70.58% gc time)
@time r2 = t2(A, n_newcol);  ## 0.011566 seconds (9 allocations: 22.889 MB, 39.08% gc time)
查看更多
女痞
4楼-- · 2019-02-23 15:12

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.

查看更多
登录 后发表回答