logo

Various Methods of Creating Vectors in Julia 📂Julia

Various Methods of Creating Vectors in Julia

Code

julia> x1=[1 2 3]
1×3 Array{Int64,2}:
 1  2  3

julia> x2=[1, 2, 3]
3-element Array{Int64,1}:
 1
 2
 3

julia> x3=[i for i in 1:3]
3-element Array{Int64,1}:
 1
 2
 3

julia> x4=[i for i in 1:3:10]
4-element Array{Int64,1}:
  1
  4
  7
 10

julia> x5=[i for i in 1:3:11]
4-element Array{Int64,1}:
  1
  4
  7
 10

x1 is a 2-dimensional array. Since it looks like a row vector, if you input only one coordinate component, it is recognized as a row vector. x2, x3, x4, x5 are 1-dimensional arrays.

  • x=[i for i in n:m] returns an array with elements ranging from $n$ to $m$ with an interval of $1$.
  • x=[i for i in n:k:m] returns an array with elements ranging from $n$ to $m$ with an interval of $k$.

The last element is the largest number that is less than or equal to $m$. This method of including a for loop inside a list to create a list is called List Comprehension in languages such as Python.

julia> x6=1:3
1:3

julia> x7=1:3:10
1:3:10

julia> x9=1:3:11
1:3:10

Although it doesn’t actually happen, you can think of arrays like x3, x4, x5 as being created as described above. As shown in the photo below, although the data types are different, they can be used in the same way as what was created above.

  • range(n,stop=m,length=k): This is exactly the same as lispace(n,m,k) in MATLAB. Let’s find out the specific differences through the example code and results below.
julia> x9=range(1,stop=10)
1:10

julia> x10=range(1,length=15)
1:15

julia> x11=range(1,stop=10,length=15)
1.0:0.6428571428571429:10.0

julia> x12=range(1,length=15,stop=10)
1.0:0.6428571428571429:10.0

Similarly, you can think of the same vector being created, even though the actual data type is different. Unlike MATLAB, you can input only one of the second or third variables, and changing the order of input doesn’t matter.

  1. First line returns a vector with the first element being $1$ and the last element $10$. Since nothing else is input, the interval between elements is $1$.
  2. Second line returns a vector with the first element being $1$ and a total of $15$ elements. The interval automatically becomes $1$, similar to a vector created with x=range(1,stop=15) or x=1:15.
  3. Third line returns a vector with the first element being $1$, the last element $10$, and a total of $15$ elements. Therefore, the interval automatically becomes $9/14=0.6428571428571429$. Since it is not an integer, it naturally returns a vector with real number elements. Also, it is the same as one created with x=1.0:0.6428571428571429:10.0.
  4. Fourth line returns a vector exactly the same as the one returned in the third line.

타언어

환경

  • OS: Windows10
  • Version: 1.5.0