Arrays
Copy vs assignment: b = a makes both names refer to the same array; use copy(a).
10.1 Creating arrays
v = [1, 2, 3] # Vector{Int64} (1-D)
row = [1 2 3] # 1×3 Matrix (space-separated)
M = [1 2; 3 4] # 2×2 Matrix (; separates rows)
M = [1 2
3 4]
A = [1 2;;; 3 4] # 3-D array syntax (1.7+)
zeros(3), ones(2, 3), fill(7, 2, 2), trues(3), falses(2)
rand(3), rand(2, 2), randn(3), rand(1:6, 10) # random
collect(1:5), Vector{Float64}(undef, 4), similar(M)
Int[] # empty typed vector
Any[1, "a", 2.0] # heterogeneous (slow)
range(0, 1, length=11) |> collect
reshape(1:6, 2, 3)10.2 Indexing & slicing (1-based, column-major)
v = [10, 20, 30, 40, 50]
v[1], v[end], v[end-1]
v[2:4] # [20, 30, 40] — slices COPY
v[[1, 3]] # fancy indexing
v[v .> 25] # logical indexing
M = reshape(1:12, 3, 4)
M[2, 3] # row 2, column 3
M[:, 1] # first column
M[1, :] # first row
M[2:3, [1, 4]]
M[end, end]
M[CartesianIndex(2, 3)]
M[7] # linear indexing (column-major order)
size(M), size(M, 1), length(M), ndims(M), axes(M), eachindex(M)10.3 Views (no copy)
col = @view M[:, 1] # a SubArray referencing M
@views s = sum(M[1:2, :]) # apply view to all slices in an expression
view(v, 2:3) .= 0 # modifies v10.4 Modifying arrays
v = [1, 2, 3]
push!(v, 4); pushfirst!(v, 0); append!(v, [5, 6])
pop!(v); popfirst!(v); insert!(v, 2, 99); deleteat!(v, 2)
splice!(v, 1:2, [7, 8])
v[1] = 100
resize!(v, 3); empty!(v); isempty(v)
filter!(iseven, v); unique!(v); sort!(v); reverse!(v)10.5 Comprehensions & generators
squares = [x^2 for x in 1:5]
evens = [x for x in 1:20 if iseven(x)]
table = [i * j for i in 1:3, j in 1:3] # 3×3 matrix
pairs_list = [(i, j) for i in 1:3 for j in i:3]
gen = (x^2 for x in 1:10^6) # lazy generator
sum(gen)10.6 Common array functions
Copy vs assignment: b = a makes both names refer to the same array; use copy(a).
sum(v), prod(v), maximum(v), minimum(v), extrema(v), argmax(v), argmin(v), findmax(v)
sum(M, dims=1) # column sums (1×n matrix)
sum(M; dims=2) # row sums
mean(v), median(v), std(v), var(v) # using Statistics
cumsum(v), cumprod(v), diff(v)
sort(v), sort(v, rev=true), sortperm(v), sort(words, by=length)
findall(>(2), v), findfirst(==(3), v), count(iseven, v), in(3, v)
vcat(a, b), hcat(a, b), cat(a, b; dims=3), [a; b], [a b]
repeat([1, 2], 3), circshift(v, 1), permutedims(M), transpose(M), M'
vec(M), reverse(v), unique(v), length(unique(v))
eltype(v), copy(v), deepcopy(nested)
mapslices(sum, M; dims=1)
eachrow(M), eachcol(M), eachslice(A; dims=3)10.7 Array types
Vector{T} = Array{T,1}, Matrix{T} = Array{T,2}, AbstractArray, SubArray (views), ranges, BitVector, SparseMatrixCSC (SparseArrays), StaticArrays.SVector (stack-allocated small arrays), OffsetArrays (custom indices), Memory{T} (1.11+ low-level buffer).