59 lines
2.0 KiB
Julia
59 lines
2.0 KiB
Julia
# This function the most simple manual way of doing matrix multiplication without builtins
|
|
# It does not take into account multithreading or any acceleration
|
|
# It does however use the least amount of memory, only allocating new memory for the sum and the results matrix
|
|
function for_loop(a, b)
|
|
n = size(a, 1)
|
|
m = size(b, 1)
|
|
if (size(a, 2) != m)
|
|
println("Matrixes not of multipliable sizes")
|
|
end
|
|
p = size(b, 2)
|
|
|
|
c = Matrix{Int}(undef, n, p)
|
|
|
|
for i in 1:n
|
|
for j in 1:p
|
|
sum = 0
|
|
for k in 1:m
|
|
a1 = a[i, k]
|
|
b1 = b[k, j]
|
|
sum = sum + (a1 * b1)
|
|
end
|
|
c[i, j] = sum
|
|
end
|
|
end
|
|
c
|
|
end
|
|
|
|
# This function is very easy as a programmer to use, as it is builtin and uses OpenBLAS, which has more advanced algorithms for doing matrix multiplication
|
|
# However, it fails under a few scenarios, where you are memory bound doing a lot of multiplications on low dimension matrixes
|
|
# as it uses much more memory even for a simple 5x5 matrix than the for loop, presumably due to allocation costs and setup/error checking
|
|
function built_in(a, b)
|
|
a * b
|
|
end
|
|
|
|
# In terms of speed, the for loop loses in pretty much every scenario, but wins initially in terms of memory usage, but as the
|
|
# matrixes begin to scale dimensions into hundreds or thousands, the builtin becomes much closer in terms of memory usage
|
|
function main()
|
|
matrix_regex = r"(\d+)x(\d+)"
|
|
|
|
println("Format is {num}x{num}. Eg: 3x3 or 100x100")
|
|
|
|
print("Dimension of first matrix: ")
|
|
input = readline()
|
|
matrix_match = match(matrix_regex, input)
|
|
matrix_1 = rand(Int, (parse(Int, matrix_match[1]), parse(Int, matrix_match[2])))
|
|
|
|
print("Dimension of second matrix: ")
|
|
input = readline()
|
|
matrix_match = match(matrix_regex, input)
|
|
matrix_2 = rand(Int, (parse(Int, matrix_match[1]), parse(Int, matrix_match[2])))
|
|
|
|
println("For loop")
|
|
@time for_loop(matrix_1, matrix_2)
|
|
|
|
println("Builtin")
|
|
@time built_in(matrix_1, matrix_2)
|
|
end
|
|
|
|
main() |