Home > Mobile >  How do I populate dynamic arrays in Julia similar to Matlab
How do I populate dynamic arrays in Julia similar to Matlab

Time:07-24

My understanding of programming languages is limited, I have started 'coding' with matlab and wanted to transfer a simulation of mine from matlab to julia because there is no licensing fee. What I would like to know is in MATLAB I can auto populate array without ever initializing an array, while I know it is an inefficient way to it, I would like to know if there is similar way to do it on Julia.

Ex in MATLAB

for a in 1:10
    x(a)=a;
end

will give me an array x = [ 1 2 3 4 5 6 7 8 9 10], is there a similar way to do that in julia? The way I have been doing it is declaring an empty array using Float64[] and append to it but it doesn't work the same way if the array is multidimensional.

my implementation in Julia for a 1D array

x = Float64[]
for a in 1:10
    append!(x,a)
end

Any help regarding this will be greatly appreciated. Thank you!!!

CodePudding user response:

MATLAB explicitly warns against the way you write this code and advises to preallocate for speed.

enter image description here

Julia, OTOH, cares more about performance and prohibits such pattern from the beginning. At the same time, it allows for more convenient and fast alternatives to do the same task.

julia> x = [a for a = 1:10] # OR x = [1:10;]
10-element Vector{Int64}:
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10

and for 2D arrays,

julia> x = [i j-1 for i = 1:5, j = 1:5] # OR x = (1:5) .  (1:5)' .- 1
5×5 Matrix{Int64}:
 1  2  3  4  5
 2  3  4  5  6
 3  4  5  6  7
 4  5  6  7  8
 5  6  7  8  9

And you have other convenience functions, like zeros(m,n), fill(val, dims), rand(Type, dims), etc., that you can use to initialize the arrays however you want.

  • Related