Julia: How to make a matrix in for loop

I’m a newbie to Julia. Before then, I used Matlab.
For the Matlab case, I wrote commands to make the matrix in the for loop, as follows:

for i=1:1:100; k(i,:)=i.^2; end

I typed the same commands in Julia, but it didn’t work.
Furthermore, I tried other commands as follows:

n=100;
k = Array{Int64, n};
for i in 1:n;
    k[i]= i;
end;

However, the error happened as follows:

MethodError: no method matching setindex!(::Type{Array{Int64, 10}}, ::Int64, ::Int64)

How to make a matrix in for loop in Julia?

>Solution :

You can follow this approach:

julia> n = 100;

julia> k = Array{Int64, 1}(undef, n);

julia> for i in 1:n
           k[i]=i
       end

julia> k
100-element Vector{Int64}:
   1
   2
   3
   4
   5
   6
   ⋮

The problem with your code is where you wrote k = Array(Int64, n). In Julia, you can define an initialized Vector using one of these approaches:

julia> Array{Int64, 1}(undef, 5)
5-element Vector{Int64}:
        1052672
 17592455528464
    68987912208
  2137636676096
              0

julia> Vector{Int64}(undef, 5)
5-element Vector{Int64}:
 2137626020784
 2137626020816
 2137626020848
 2137626020880
          3063

julia> zeros(Int64, 5)
5-element Vector{Int64}:
 0
 0
 0
 0
 0

julia> ones(Int64, 5)
5-element Vector{Int64}:
 1
 1
 1
 1
 1

In the above, I created some initialized Vectors with specific attributes, all with length 5. Note that the meaning of Array{Int64, 1}(undef, 5) can be translated to create an object of type Array with the number of dimensions equal to 1 (a Vector in fact) and put 5 undefined values of type Int64 in it.
But if you want to make a Matrix (considering the way you wrote k[i]= i, it seems to me that you want an nx1 dimensional Matrix), then you can do the following:

julia> n = 100;

julia> k = Array{Int64, 2}(undef, n, 1);

julia> for i in 1:n
           k[i]=i
       end

julia> k
100×1 Matrix{Int64}:
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
   ⋮

Note that the type of k is Matrix with element type Int64. using the following approaches, you can create an initialized Matrix:

julia> Array{Int64, 2}(undef, 5, 1)
5×1 Matrix{Int64}:
 1
 2
 3
 4
 5

julia> Matrix{Int64}(undef, 5, 1)
5×1 Matrix{Int64}:
             1
             4
 2137623855824
 2137623855888
             0

julia> zeros(5, 1)
5×1 Matrix{Float64}:
 0.0
 0.0
 0.0
 0.0
 0.0

julia> ones(5, 1)
5×1 Matrix{Float64}:
 1.0
 1.0
 1.0
 1.0
 1.0

In all above, 5, 1 specifies the matrix’s dimension.


Additional Note

Note that you can assign values to a nxn matrix using single indexing:

julia> k = [5; 7;;8; 9]
2×2 Matrix{Int64}:
 5  8
 7  9

julia> for i in eachindex(k)
           k[i]=i
       end

julia> k
2×2 Matrix{Int64}:
 1  3
 2  4

julia> k
2×2 Matrix{Int64}:
 1  3
 2  4

In the above, the eachindex(k) creates a UnitRange which contains values from 1 up to 4 (since the k has 4 elements) and is iterable.

Leave a Reply