CodeToLive

Julia Arrays & Matrices

Master array operations and linear algebra in Julia.

Creating Arrays

# 1D array (vector)
v = [1, 2, 3, 4]

# 2D array (matrix)
m = [1 2; 3 4]

# Range
r = 1:5  # 1, 2, 3, 4, 5

# Array with type annotation
a = Float64[1, 2, 3]

Array Operations

# Element-wise operations
a = [1, 2, 3]
b = [4, 5, 6]
a + b  # [5, 7, 9]
a .* b # [4, 10, 18] (element-wise multiplication)

# Dot product
using LinearAlgebra
dot(a, b)  # 32

# Matrix multiplication
A = [1 2; 3 4]
B = [5 6; 7 8]
A * B

Indexing and Slicing

a = [10, 20, 30, 40, 50]

# Get element
a[1]  # 10 (Julia is 1-indexed)

# Get range
a[2:4]  # [20, 30, 40]

# Last element
a[end]  # 50

# Matrix indexing
m = [1 2; 3 4]
m[1, 2]  # 2

Array Comprehensions

# Simple comprehension
squares = [x^2 for x in 1:5]  # [1, 4, 9, 16, 25]

# 2D comprehension
matrix = [i + j for i in 1:3, j in 1:4]

Common Array Functions

a = [3, 1, 4, 1, 5]

length(a)  # 5
sum(a)     # 14
maximum(a) # 5
sort(a)    # [1, 1, 3, 4, 5]

# Reshape
reshape(1:9, 3, 3)
← Back to Tutorials