Previously we looked at simple operations with two-dimensional arrays and two-dimensional matrices.
In this section I will also discuss some further topics to cover multi-dimensional arrays, broadcasting and of handling sparse arrays but first I wish to introduce the concept of vectorized and devectorized code.
Consider the following code to add two vectors:
function vecadd1(a,b,c,N) for i = 1:N c = a + b end end function vecadd2(a,b,c,N) for i = 1:N, j = 1:length(c) c[j] = a[j] + b[j] end end julia> A = rand(2); B = rand(2); C = zeros(2); julia> @elapsed vecadd1(A,B,C,100000000) @elapsed vecadd1(A,B,C,100000000) # => 18.418755286 julia> @elapsed vecadd2(A,B,C,100000000) @elapsed vecadd2(A,B,C,100000000) # => 0.524002398
Why the difference in timings? The function vecadd1()
uses the array plus operation to perform the calculation whereas vecadd2()
explicitly loops through the arrays and performs a series...