Class: Matrix

Inherits:
Object show all
Defined in:
lib/epitools/core_ext/matrix.rb

Overview

Matrix extensions

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.ones(*dims) ⇒ Object

Build an array of 1’s



25
26
27
# File 'lib/epitools/core_ext/matrix.rb', line 25

def self.ones(*dims)
  build(*dims) { 1 }
end

.random(*dims) ⇒ Object

Create a matrix of the specified size full of random numbers.



32
33
34
# File 'lib/epitools/core_ext/matrix.rb', line 32

def self.random(*dims)
  build(*dims) { rand }
end

Instance Method Details

#blit!(submatrix, top, left) ⇒ Object Also known as: overlay!

Overlay one matrix onto another



83
84
85
86
87
88
89
# File 'lib/epitools/core_ext/matrix.rb', line 83

def blit!(submatrix, top, left)
  submatrix.each_row.with_index do |row, y|
    row.each.with_index do |elem, x|
      self[top+y,left+x] = elem
    end
  end
end

#each_rowObject

Iterate over rows (takes a block or returns an Enumerator)



46
47
48
49
50
51
52
# File 'lib/epitools/core_ext/matrix.rb', line 46

def each_row
  return to_enum(:each_row) unless block_given?

  (0...row_count).each do |num|
    yield row(num)
  end
end

Print the matrix to the STDOUT.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/epitools/core_ext/matrix.rb', line 57

def print(header=true, separator=" ")
  max_width = map {|num| num.to_s.size }.max

  case first
  when Integer
    justify = :rjust
  when Float
    justify = :ljust
  else
    raise "Unknown matrix element type: #{first.class}"
  end

  # print it!
  puts "#{size.join("x")} matrix:" if header

  rows.each do |row|
    puts "  " + row.map { |n| n.to_s.send(justify, max_width) }.join(separator)
  end

  puts
end

#sizeObject

The size of the matrix, returned as ‘[rows, columns]`.



39
40
41
# File 'lib/epitools/core_ext/matrix.rb', line 39

def size
  [row_size, column_size]
end