Matrix Operations in Julia

a = [1 2 3; 4 5 6]
b = [3 4 5; 6 7 8]
# element wise subtraction
c = b-a
println(c)

# element wise square
println(c.^2)
println(size(c))


# sum all elements of a matrix
d  = [1 3 7; 9 6 1]
println(sum(d))

# sum rows of matrix
println(sum(d, dims=1))

# sum columns of matrix
println(sum(d, dims=2))

Outputs

[2 2 2; 2 2 2]
[4 4 4; 4 4 4]
(2, 3)
27
[10 9 8]
[11; 16]

 

Slicing the matrix

# Slice matrix
a = [1 2 3;
    4 5 6;
    7 8 9]


println(a[1, :]) # first row of matrix
println(a[3, :]) # third row of matrix
println(a[:, 1]) # first column of matrix
println(a[:, 2:end]) # last 2 columns of matrix
println(a[:, 1:end-1]) # all columns of matrix except the last one
println(a[1:end-1, :]) # all rows of the matrix except the last one

Output:

[1, 2, 3]
[7, 8, 9]
[1, 4, 7]
[2 3; 5 6; 8 9]
[1 2; 4 5; 7 8]
[1 2 3; 4 5 6]

Multiply a matrix by a scalar

a = [1 2 3; 4 5 6];
println(a*5);

Output:

[5 10 15; 20 25 30]

Doing element wise Int operation

A = [1.0 -0.3; 3.9 4.5];

println("Original ", A)

println("Round: ", round.(Int, A))

println("Floor: ", floor.(Int, A))

println("Truncate: ", trunc.(Int, A))

println("Ceil: ", ceil.(Int, A))

Output:

Original [1.0 -0.3; 3.9 4.5]
Round: [1 0; 4 4]
Floor: [1 -1; 3 4]
Truncate: [1 0; 3 4]
Ceil: [1 0; 4 5]