typestar

Matrices in Julia

Built-in 2-D arrays: spaces for columns, ; for rows.

# Matrices are built in; spaces separate columns, ; separates rows.
counts = [4 7 2; 9 1 5]
println(size(counts))

# Indexing is row, column; : takes a whole slice.
println(counts[2, 1])
println(counts[:, 2])

# ' transposes; broadcasting works elementwise on the whole array.
doubled = counts .* 2
println(doubled)
println(counts')

println("Grand total: ", sum(counts))

How it works

  1. [4 7 2; 9 1 5] is a 2x3 Matrix; size reports it.
  2. Indexing is [row, col]; : slices a whole dimension.
  3. ' transposes; broadcasting doubles every cell.

The run, in numbers

Lines
14
Characters to type
371
Tokens
64
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 59 seconds.

Type this snippet

Step 3 of 3 in Broadcasting, step 15 of 27 in Language basics.

← Previous Next →

Matrices in other languages