'Julia vector question: generating sequential intergers and the same values

I have a beginner Julia question regarding generating two types of vectors:

  1. How to I generate a vector consisting out of n of the same elements, without having to type it out manually? For example, how do I generate a vector v consisting out of 7 times the number 5, thus v = [5,5,5,5,5,5,5].

  2. How do I generate a vector with n sequential integers starting at integer x, again without having to type it out manually? For example how do I generate a vector z with 10 sequential integers starting at 1, thus z = [1,2,3,4,5,6,7,8,9,10].



Solution 1:[1]


julia> v = fill(5, 7); 

julia> @show v;
v = [5, 5, 5, 5, 5, 5, 5]

julia> z = collect(1:10);

julia> @show z;
z = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Note that in the second case, often you can operate on the range 1:10 directly without having to do a collect on it (z = 1:10). 1:10 is a Range type, that works by saving just the starting and ending points, without allocating memory for all 10 values. collect converts that into a full Vector, which allocates memory for each element.

Solution 2:[2]

  1. To generate the example: v = repeat([5],7])
  2. To generate the example: z = [1:10;]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Daniël