Homework 3: Matrix multiplication

This assignment teaches linear algebra operations via explicit for loops.

Write a function that accepts as input two rank-3 tensors A_kil and B_ljk, and that calculate the traces T_ij := A_kil B_ljk.

  • Calculate this trace via explicit for loops
  • Use reshape to calculate the traces also via built-in linear algebra calls, i.e. without for loops
  • Compare code size, clarity, time needed to develop the code, and performance (using @time, for reasonably large matrices)

In [23]:
function trace1{T<:Number}(A::Array{T,3},B::Array{T,3})
    if size(A)[1] != size(B)[end] || size(A)[end] != size(B)[1]
        throw(BoundsError())
    end
    imax=size(A)[2]
    jmax=size(A)[2]
    lmax=size(A)[end]
    kmax=size(A)[1]
    s=zeros(T,imax,jmax)
    for i=1:imax,j=1:jmax,k=1:kmax,l=1:lmax
        s[i,j] += A[k,i,l]*B[l,j,k]
    end
    s
end


Out[23]:
trace1 (generic function with 1 method)

In [ ]:
function trace

In [33]:
A = reshape(collect(1:27),3,3,3);
B = reshape(collect(28:(28+27-1)),3,3,3);

In [35]:
@time trace1(A,B)


  
Out[35]:
3x3 Array{Int64,2}:
 3870  4167  4464
 4896  5274  5652
 5922  6381  6840
0.000010 seconds (149 allocations: 10.292 KB)

In [22]:
zeros(Float64,2,2)[1,1]


Out[22]:
0.0

In [21]:
for i=1:2,j=1:2
    println(i+j)
end


2
3
3
4

In [ ]: