Binding vectors to array

Hey, I’m new to Julia and not sure about some issues regarding arrays. One of these is this one:

I just want to bind several vectors with zeros to an array. Their length is given in another array like that:

length = [10 20 30 40....]

Now I do the following:

zeroarray = zeros(length[1])
zeroarray = vcat([zeroarray], zeros(length[2])

for i in 3:length(length)
zeroarray = vcat(zeroarray, zeros(length[i])
end

This looks not like the appropriate approach to me. I would like to know how to formulate this properly. For explanation, this is the equivalent in python:

import numpy as np

length = [10, 20, 30, 40,....]
zeroarray = [np.zeros(length[0])]

for i in range(1, len(length)):
zeroarray.append(np.zeros(length[i]))

I would be very thankful for further advice!

Does

zeros.(length) work? I.e. using broadcasting.

You probably want to write length using commas instead of spaces, to give a vector instead of a matrix.

1 Like

(By the way, it would be useful to see what kind of output you are looking for.)

Edit: I misunderstood your question. You can do this, though, which is similar:

zeroarray = vcat((zeros(n) for n in lengths)...)

Old answer:

First of all, you shouldn’t call your vector length, since that is the name of a very important function in julia (and in many other languages.)

The best approach seems to me to be a comprehension:

lengths = [10, 20, 30, 40]  # or lengths = 10:10:40 
zeroarray = [zeros(n) for n in lengths]

In Python you would do exactly the same:

zeroarray = [np.zeros(n) for n in lengths]

Actually, the best (and fastest) solution is probably

zeroarray = zeros(sum(lengths))

Oh yeah, that does work indeed! I completely forgot about the possibility of using zeros.() . And yes, I want to write it with commas :slight_smile:.
Thank you very much!

No, you got my question right :smiley:. Your original answer is what I was looking for. Thanks!

Oh, yeah. This is clearly the best solution, now that the original question has been clarified.