Julia, similarly to most scientific languages, has a very convenient syntax for array slicing. Consider the following example that sums each column of a two-dimensional matrix. First, we will define a function that sums the elements of a vector to produce a scalar. We will then use this function inside a loop to sum the columns of a matrix, passing each column one by one to our vector adder as follows:
function sum_vector(x::Array{Float64, 1})
s = zero(eltype(x))
for i in 1:length(x)
s = s + x[i]
end
return s
end
function sum_cols_matrix(x::Array{Float64, 2})
num_cols = size(x, 2)
s = zeros(num_cols)
for i = 1:num_cols
s[i] = sum_vector(x[:, i])
end
return s
end
The x[:, j] syntax denotes all the row elements of the jth column. In other words, it slices a matrix into its individual columns. Benchmarking this function, we will...