Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide modified versions of ruby's matmul #24

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/ruby/matmul.flat_array.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
def matgen(n)
tmp = 1.0 / n / n
return Array.new(n * n) do |i|
k = i / n
j = i % n
tmp * (k - j) * (k + j)
end
end

def matmul(a, ah, aw, b, _bh, bw)
c = Array.new(ah * bw, 0)
(0...ah).each do |ay|
# a-y-offset
ayo = ay * aw
cyo = ay * bw
(0...aw).each do |ax|
# a-cell
ac = a[ayo + ax]
# b-y-offset
byo = ax * bw
(0...bw).each do |bx|
c[cyo + bx] += ac * b[byo + bx]
end
end
end
return c
end

n = 1500
if ARGV.length >= 1
n = ARGV[0].to_i
end
n = n / 2 * 2
a = matgen(n)
b = matgen(n)
c = matmul(a, n, n, b, n, n)
puts c[n/2 * n + n/2]
36 changes: 36 additions & 0 deletions src/ruby/matmul.inline.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
def matgen(n)
tmp = 1.0 / n / n
# initializes the array inline
return Array.new(n) do |i|
Array.new(n) do |j|
tmp * (i - j) * (i + j)
end
end
end

def matmul(a, b)
m = a.length
n = a[0].length
p = b[0].length
return Array.new(m) do |i|
ai = a[i]
Array.new(p) do |j|
acc = 0
(0...n).each do |k|
# the column access here is killing it
acc += ai[k] * b[k][j]
end
acc
end
end
end

n = 1500
if ARGV.length >= 1
n = ARGV[0].to_i
end
n = n / 2 * 2
a = matgen(n)
b = matgen(n)
c = matmul(a, b)
puts c[n/2][n/2]