vincet
vincet

Reputation: 977

Julia : How to fill a matrix row by row in julia

I have 200 vectors; each one has a length of 10000.

I want to fill a matrix such that each line represents a vector.

Upvotes: 2

Views: 3288

Answers (2)

Michael Ohlrogge
Michael Ohlrogge

Reputation: 10980

If your vectors are already stored in an array then you can use vcat( ) here:

A = [rand(10000)'  for idx in 1:200]
B = vcat(A...)

Upvotes: 4

isebarn
isebarn

Reputation: 3940

Julia stores matrices in column-major order so you are going to have to adapt a bit to that

If you have 200 vectors of length 100000 you should make first an empty vector, a = [], this will be your matrix Then you have to vcat the first vector to your empty vector, like so

v = your vectors, however they are defined 
a = []
a = vcat(a, v[1])

Then you can iterate through vectors 2:200 by

for i in 2:200
    a = hcat(a,v[i])
end 

And finally transpose a

a = a'

Alternatively, you could do

a = zeros(200,10000)

for i in 1:length(v)
    a[i,:] = v[i]
end 

but I suppose that wont be as fast, if performance is at all an issue, because as I said, julia stores in column major order so access will be slower

EDIT from reschu's comment

a = zeros(10000,200)

for i in 1:length(v)
    a[:,i] = v[i]
end 

a = a'

Upvotes: 2

Related Questions