What is the easiest way to create a vector with elements c1, c2, c3, ..., c1000

What is the easiest way to create a vector with elements c1, c2, c3, …, c1000

What do you mean with elements c1, … ? If they are concatenated letters and numbers you could do:

["c"*string(i) for i in 1:1000]
1 Like

If you mean that you have variables with these names then could use metaprogramming, e.g. if they are global variable you could use [eval(Symbol(:c, i)) for i = 1:1000].

However, in this case I would strongly urge you to re-think your code structure, and use a data structure like an array to begin with, not zillions of variables with different names.

1 Like

See also: Creating a list of symbols using a comprehension

This generates a 1000-element vector of random values:

julia> c = rand(1000)
1000-element Vector{Float64}:
 0.5647389507376179
 0.18111369557568624
 0.8727956817721915
 0.22835918313738857
 0.2497456673875318
 0.9181345802141495
 0.6070152421017295
 0.7392933645606421
 0.6196225753003001
 0.280834358470918
 0.5100254226676332
 0.9816413192259156
 0.6700354181216701
 ⋮
 0.7927264973496545
 0.17482774804441292
 0.5294179310633541
 0.858583692569896
 0.1277444673489978
 0.9421766813356514
 0.48838842851956077
 0.3351709485105858
 0.4807149298155149
 0.3762423751393996
 0.45065876319192155
 0.09364657772281326

You can access c_1, c_2, c_3, and c_{1000} by using square brackets like so:

julia> c[1], c[2], c[3], c[1000]
(0.5647389507376179, 0.18111369557568624, 0.8727956817721915, 0.09364657772281326)

If there’s some relation between the vector index i and the element values of c, you can use an array comprehension to populate c in accordance with that. For example, the elements of this vector follow the relation, c_i = i^2.

julia> c = [i^2 for i = 1:1000]
1000-element Vector{Int64}:
       1
       4
       9
      16
      25
      36
      49
      64
      81
     100
     121
     144
     169
       ⋮
  978121
  980100
  982081
  984064
  986049
  988036
  990025
  992016
  994009
  996004
  998001
 1000000
2 Likes

A post was split to a new topic: Encouraging clearer questions on discourse?

I’d note that common practice is to initialize an array with e.g. Vector{Type}(undef, 1000), rather than rand(1000). rand will take more time to generate the random numbers and is conceptually less clear. ones(1000) also works.

Nooo don’t introduce a newbie to undef allocation yet! :sweat_smile:

It’s usually best to initiate/fill the array immediately upon allocating it, which is what zeros, ones, fill, rand, and comprehensions do.

Consider undef allocation for serious optimization work, but do it with caution because if you do it wrong, bad things can happen :warning:

6 Likes