class Array

Classes and Modules #

Public Instance Methods

to_nm(shape = nil, dtype = nil, stype = :dense) click to toggle source

Convert a Ruby Array to an NMatrix.

You must provide a shape for the matrix as the first argument.

Arguments:

shape

Array describing matrix dimensions (or Fixnum for square).

If not provided, will be intuited through #shape.
dtype

Override data type (e.g., to store a Float as :float32

instead of :float64) -- optional.
stype

Optional storage type (defaults to :dense)

# File lib/nmatrix/monkeys.rb, line 46
def to_nm(shape = nil, dtype = nil, stype = :dense)
  elements = self.dup

  guess_dtype = ->(type) {
    case type
    when Fixnum   then :int64
    when Float    then :float64
    when Complex  then :complex128
    end
  }

  guess_shape = lambda { |shapey; shape|
    # Get the size of the current dimension
    shape = [shapey.size]
    shape << shapey.map {|s|
      if s.respond_to?(:size) && s.respond_to?(:map)
        guess_shape.call(s)
      else
        nil
      end
    }
    if shape.last.any? {|s| (s != shape.last.first) || s.nil?}
      shape.pop
    end
    if (shape.first != shape.last) && shape.last.all? {|s| s == shape.last.first}
      shape[-1] = shape.last.first
    end
    shape.flatten
  }

  unless shape
    shape = guess_shape.call(elements)
    elements.flatten!(shape.size - 1)
    if elements.flatten != elements
      dtype = :object
    else
      dtype ||= guess_dtype[elements[0]]
    end
  end

  dtype ||= guess_dtype[self[0]]

  matrix = NMatrix.new(:dense, shape, elements, dtype)

  if stype != :dense then matrix.cast(stype, dtype) else matrix end
end