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.77 lib/epitools/core_ext/matrix.rb
epitools-0.5.75 lib/epitools/core_ext/matrix.rb
epitools-0.5.74 lib/epitools/core_ext/matrix.rb
epitools-0.5.73 lib/epitools/core_ext/matrix.rb
epitools-0.5.72 lib/epitools/core_ext/matrix.rb
epitools-0.5.71 lib/epitools/core_ext/matrix.rb
epitools-0.5.70 lib/epitools/core_ext/matrix.rb
epitools-0.5.69 lib/epitools/core_ext/matrix.rb
epitools-0.5.68 lib/epitools/core_ext/matrix.rb
epitools-0.5.67 lib/epitools/core_ext/matrix.rb
epitools-0.5.66 lib/epitools/core_ext/matrix.rb
epitools-0.5.65 lib/epitools/core_ext/matrix.rb
epitools-0.5.64 lib/epitools/core_ext/matrix.rb
epitools-0.5.63 lib/epitools/core_ext/matrix.rb
epitools-0.5.61 lib/epitools/core_ext/matrix.rb
epitools-0.5.60 lib/epitools/core_ext/matrix.rb
epitools-0.5.59 lib/epitools/core_ext/matrix.rb
epitools-0.5.58 lib/epitools/core_ext/matrix.rb
epitools-0.5.57 lib/epitools/core_ext/matrix.rb
epitools-0.5.56 lib/epitools/core_ext/matrix.rb