More about matrices
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.
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) ...
Get Julia: High Performance Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.