Sha256: 1fb3771420d9f3e9b16503804b24329777828717a31ab8cb7885c8f1d3731fd6

Contents?: true

Size: 1.24 KB

Versions: 60

Compression:

Stored size: 1.24 KB

Contents

require 'matrix'

#
# Matrix extensions
#
class Matrix

  alias_class_method :zeros, :zero
  alias_class_method :zeroes, :zero

  #
  # Create a matrix of the specified size full of random numbers.
  #
  def self.random(*dims)
    build(*dims) { rand }
  end


  #
  # The size of the matrix, returned as `[rows, columns]`.
  #
  def size
    [row_size, column_size]
  end

  #
  # Print the matrix to the STDOUT.
  #
  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

  alias_method :draw, :print

  #
  # Allow mathematical operations (*, /, +, -) with a regular number on the right side.
  #
  # eg: Matrix.zero(3) + 5
  #
  %w[* / + -].each do |op|
    class_eval %{
      def #{op}(other)
        case other
        when Fixnum, Float
          map { |e| e #{op} other }
        else
          super(other)
        end
      end
    }
  end

  public :[]=

end

Version data entries

60 entries across 60 versions & 1 rubygems

Version Path
epitools-0.5.98 lib/epitools/core_ext/matrix.rb
epitools-0.5.97 lib/epitools/core_ext/matrix.rb
epitools-0.5.96 lib/epitools/core_ext/matrix.rb
epitools-0.5.95 lib/epitools/core_ext/matrix.rb
epitools-0.5.94 lib/epitools/core_ext/matrix.rb
epitools-0.5.93 lib/epitools/core_ext/matrix.rb
epitools-0.5.92 lib/epitools/core_ext/matrix.rb
epitools-0.5.91 lib/epitools/core_ext/matrix.rb
epitools-0.5.90 lib/epitools/core_ext/matrix.rb
epitools-0.5.89 lib/epitools/core_ext/matrix.rb
epitools-0.5.88 lib/epitools/core_ext/matrix.rb
epitools-0.5.87 lib/epitools/core_ext/matrix.rb
epitools-0.5.86 lib/epitools/core_ext/matrix.rb
epitools-0.5.85 lib/epitools/core_ext/matrix.rb
epitools-0.5.84 lib/epitools/core_ext/matrix.rb
epitools-0.5.83 lib/epitools/core_ext/matrix.rb
epitools-0.5.82 lib/epitools/core_ext/matrix.rb
epitools-0.5.81 lib/epitools/core_ext/matrix.rb
epitools-0.5.79 lib/epitools/core_ext/matrix.rb
epitools-0.5.78 lib/epitools/core_ext/matrix.rb