Class: Array

Inherits:
Object show all
Defined in:
lib/nmatrix/monkeys.rb

Overview

Classes and Modules #

Instance Method Summary collapse

Instance Method Details

#to_nm(shape = nil, dtype = nil, stype = :dense) ⇒ Object

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)



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/nmatrix/monkeys.rb', line 44

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