Class: RMatrix::Matrix

Inherits:
Object
  • Object
show all
Includes:
Enumerable, Indices
Defined in:
lib/rmatrix/matrix.rb,
lib/rmatrix/typecode.rb,
lib/rmatrix/shortcuts.rb

Direct Known Subclasses

Vector

Defined Under Namespace

Modules: Typecode

Constant Summary collapse

OPERATIONS_MAP =
{
  :& => 'and',
  :^ => 'xor',
  :| => 'or'
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Indices

#[], #build_result_map, #indexify, #raw, #unmap_args, #unmap_index

Constructor Details

#initialize(source, typecode = Typecode::FLOAT, column_map: nil, row_map: nil) ⇒ Matrix

Returns a new instance of Matrix.



12
13
14
15
16
# File 'lib/rmatrix/matrix.rb', line 12

def initialize(source, typecode=Typecode::FLOAT, column_map: nil, row_map: nil)
  self.typecode = typecode
  self.narray   = two_dimensional(source, typecode)
  self.row_map, self.column_map = row_map, column_map
end

Instance Attribute Details

#column_mapObject

Returns the value of attribute column_map.



9
10
11
# File 'lib/rmatrix/matrix.rb', line 9

def column_map
  @column_map
end

#invert_next_operationObject

Returns the value of attribute invert_next_operation.



9
10
11
# File 'lib/rmatrix/matrix.rb', line 9

def invert_next_operation
  @invert_next_operation
end

#matrixObject



18
19
20
# File 'lib/rmatrix/matrix.rb', line 18

def matrix
  @matrix ||= narray.empty? ? narray : NMatrix.refer(narray)
end

#narrayObject

Returns the value of attribute narray.



9
10
11
# File 'lib/rmatrix/matrix.rb', line 9

def narray
  @narray
end

#row_mapObject

Returns the value of attribute row_map.



9
10
11
# File 'lib/rmatrix/matrix.rb', line 9

def row_map
  @row_map
end

#typecodeObject

Returns the value of attribute typecode.



9
10
11
# File 'lib/rmatrix/matrix.rb', line 9

def typecode
  @typecode
end

Class Method Details

.[](*inputs, typecode: Typecode::FLOAT, row_map: nil, column_map: nil) ⇒ Object



340
341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/rmatrix/matrix.rb', line 340

def self.[](*inputs, typecode: Typecode::FLOAT, row_map: nil, column_map: nil)
  if inputs.length == 1 && Matrix === inputs[0]
    inputs[0]
  elsif inputs.length == 1 && [String, Symbol].include?(inputs[0].class)
    if ['byte', 'sint', 'int', 'sfloat', 'float', 'scomplex', 'complex', 'object'].include?(inputs[0])
      ->(*source){ Matrix.new(source, inputs[0], row_map: row_map, column_map: column_map)}
    else
      Matrix.new(inputs[0], typecode, row_map: row_map, column_map: column_map)
    end
  else
    Matrix.new(inputs, typecode, row_map: row_map, column_map: column_map)
  end
end

._load(arg) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rmatrix/matrix.rb', line 36

def self._load arg
  split_index, buffer, index = 0, '', arg.length - 1
  split = Array.new(3)
  while split_index < 3
    case char = arg[index]
    when ':'
      split[split_index] = buffer.reverse.to_i
      split_index += 1
      buffer = ''
    else buffer << char
    end
    index -= 1
  end
  arg[index+1..-1] = ''
  self.new(NArray.to_na(arg, split[0]).reshape(split[2], split[1]), split[0])
end

.blank(rows: 1, columns: 1, typecode: Typecode::FLOAT, initial: 0) ⇒ Object



22
23
24
25
26
# File 'lib/rmatrix/matrix.rb', line 22

def self.blank(rows: 1, columns: 1, typecode: Typecode::FLOAT, initial: 0)
  source = self.new(NArray.new(typecode, columns, rows), typecode)
  source.narray[]= initial unless source.empty?
  source
end

.gen_delegator(name) ⇒ Object



384
385
386
387
388
389
390
391
392
# File 'lib/rmatrix/matrix.rb', line 384

def self.gen_delegator(name)
  define_method(name) do |*args, &blk|
    result = matrix.send(name, *args, &blk)
    case result
    when NArray then Matrix.new(result, typecode)
    else result
    end
  end
end

.gen_matrix_delegator(name) ⇒ Object



365
366
367
368
369
# File 'lib/rmatrix/matrix.rb', line 365

def self.gen_matrix_delegator(name)
  define_method(name) do |*args, &blk|
    Matrix.new(matrix.send(name, *args, &blk), typecode)
  end
end

.gen_mutator(name) ⇒ Object



358
359
360
361
362
363
# File 'lib/rmatrix/matrix.rb', line 358

def self.gen_mutator(name)
  define_method(name) do |*args, &blk|
    matrix.send(name, *args, &blk)
    self
  end
end

.gen_typeconstructor(name) ⇒ Object



394
395
396
397
398
# File 'lib/rmatrix/matrix.rb', line 394

def self.gen_typeconstructor(name)
  define_singleton_method(name) do
    ->(*source){ Matrix.new(source, name.to_s) }
  end
end

.identity(size) ⇒ Object



121
122
123
124
# File 'lib/rmatrix/matrix.rb', line 121

def self.identity(size)
  blank = self.blank(rows: size, columns: size)
  blank.diagonal(1)
end

.ones(rows: 1, columns: 1) ⇒ Object



126
127
128
# File 'lib/rmatrix/matrix.rb', line 126

def self.ones(rows: 1, columns: 1)
  self.blank(rows: rows, columns: columns, initial: 1)
end

.seed(seed) ⇒ Object



433
434
435
# File 'lib/rmatrix/matrix.rb', line 433

def self.seed(seed)
  NArray.srand(seed)
end

.translate_op(op) ⇒ Object



405
406
407
# File 'lib/rmatrix/matrix.rb', line 405

def self.translate_op(op)
  OPERATIONS_MAP.fetch(op, op)
end

Instance Method Details

#*(other) ⇒ Object



249
250
251
252
253
254
255
256
# File 'lib/rmatrix/matrix.rb', line 249

def *(other)
  if other.kind_of?(Matrix)
    raise "Matrix A columns(#{self.columns}) != Matrix B rows(#{other.columns})" if other.rows != self.columns
    Matrix.new(self.matrix * other.matrix, typecode)
  else
    Matrix.new(apply_scalar(:*, other), typecode)
  end
end

#==(other) ⇒ Object



262
263
264
# File 'lib/rmatrix/matrix.rb', line 262

def ==(other)
  self.narray == Matrix[other].narray
end

#_dump(level) ⇒ Object



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

def _dump(level)
   narray.to_s << ':' << columns.to_s << ':' << rows.to_s << ':' << narray.typecode.to_s
end

#absObject



95
96
97
# File 'lib/rmatrix/matrix.rb', line 95

def abs
  (self ** 2) ** 0.5
end

#adjointObject Also known as: A



245
246
247
# File 'lib/rmatrix/matrix.rb', line 245

def adjoint
  self.cofactor_matrix.transpose
end

#box_lines(lines, add_dots) ⇒ Object



270
271
272
# File 'lib/rmatrix/matrix.rb', line 270

def box_lines(lines, add_dots)
  "[#{lines.map{|l| "[#{l}#{add_dots ? ' ...' : '' }]"}.join(",\n  ")}]"
end

#coerce(other) ⇒ Object



99
100
101
102
# File 'lib/rmatrix/matrix.rb', line 99

def coerce(other)
  self.invert_next_operation = true
  [self, other]
end

#cofactor_matrix(*args) ⇒ Object Also known as: C



220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/rmatrix/matrix.rb', line 220

def cofactor_matrix(*args)
  return cofactor(*args) if args.length == 2

  result = []
  rows.times do |i|
    result << []
    columns.times do |j|
      result[i] << cofactor(i, j)
    end
  end
  return Matrix.new(result, typecode)
end

#columnsObject Also known as: cols



112
113
114
# File 'lib/rmatrix/matrix.rb', line 112

def columns
  self.shape.first
end

#concat(*others, rows: true) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/rmatrix/matrix.rb', line 138

def concat(*others, rows: true)
  others.map!{|o| Matrix === o ? o.narray : NArray.to_na(o)}

  joined = case rows
  when true
    # raise "Rows must match #{self.rows}, #{others.map(&:rows)}" unless [self.rows, *others.map(&:shape).map(&:last)].uniq.count.one?
    height = self.rows + others.map(&:shape).map(&:last).inject(:+)
    width  = others[0].shape.first
    joined = ::NArray.new(typecode, width, height)
    joined[true, 0...self.rows] = self.narray
    current_row = self.rows
    others.each do |slice|
      slice_height = slice.shape[1]
      joined[true, current_row...current_row+slice_height] = slice
      current_row += slice_height
    end
    joined
  else
    width  = self.columns + others.map(&:shape).map(&:first).inject(:+)
    height = others[0].shape.last
    joined = ::NArray.new(typecode, width, height)
    joined[0...self.columns, true] = self.narray
    current_col = self.columns
    others.each do |slice|
      slice_width = slice.shape[0]
      joined[current_col...current_col+slice_width, true] = slice
      current_col += slice_width
    end
    joined
    # raise "Rows must match #{self.columns}, #{others.map(&:columns)}" unless [self.columns, *others.map(&:columns)].uniq.count.one?
  end

  Matrix.new(joined, typecode)
end

#condensed(sz = 10, sig = 6, vdots = '\\vdots', cdots = '\\cdots', ddots = '\\ddots') ⇒ Object



308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/rmatrix/matrix.rb', line 308

def condensed(sz=10, sig=6, vdots='\\vdots', cdots='\\cdots', ddots='\\ddots')
  width  = [sz, self.cols].min
  height = [sz, self.rows].min
  insert_cdots = self.cols > sz
  insert_vdots = self.rows > sz

  width  += 1 if insert_cdots
  height += 1 if insert_vdots

  blank = M.blank(rows: height, columns: width, typecode: Typecode::OBJECT)
  blank.narray[0...width, 0...height] = self.narray[0...width, 0...height]

  blank.narray[0...width, -1] = self.narray[0...width, -1]
  blank.narray[-1,0...height] = self.narray[-1, 0...height]

  blank.narray[0...width, -2] = vdots if insert_vdots
  blank.narray[-2, 0...height] = cdots if insert_cdots

  if insert_cdots && insert_vdots
    blank.narray[-2, -2] = ddots
    blank.narray[-1, -2] = vdots
    blank.narray[-2, -1] = cdots
    blank.narray[-1, -1] = self.narray[-1, -1]
  end

  blank.narray.to_a.map{|line| (sig ? Array(line).map{|v| Numeric === v ? to_significant_figures(v,sig) : v } : Array(line))}
end

#determinantObject Also known as: D



233
234
235
236
237
238
239
240
241
242
243
# File 'lib/rmatrix/matrix.rb', line 233

def determinant
  raise "Cannot calculate determinant of non-square matrix" unless columns == rows
  return self.raw[0, 0] * self.raw[1, 1]- self.raw[0, 1] * self.raw[1, 0] if(self.columns == 2)
  sign = 1
  det = 0
  self.columns.times do |i|
    det += sign * self.raw[0,i] * self.minor(0, i).determinant
    sign *= -1
  end
  return det
end

#diag(dim = 0) ⇒ Object



116
117
118
119
# File 'lib/rmatrix/matrix.rb', line 116

def diag(dim=0)
  raise "Must be square matrix" unless self.shape[0] == self.shape[1]
  Matrix.new((self.class.identity(self.shape[0]).mult self).sum(dim))
end

#each(&block) ⇒ Object



53
54
55
56
57
58
59
60
# File 'lib/rmatrix/matrix.rb', line 53

def each(&block)
  e = Enumerator.new do |enum|
    matrix.each do |elm|
      enum << elm
    end
  end
  block_given? ? e.each(&block) : e
end

#each_column(&block) ⇒ Object



62
63
64
65
66
67
68
69
# File 'lib/rmatrix/matrix.rb', line 62

def each_column(&block)
  e = Enumerator.new do |enum|
    (0...self.columns).each  do |i|
      enum << self.raw[true, i]
    end
  end
  block_given? ? e.each(&block) : e
end

#each_row(&block) ⇒ Object



71
72
73
74
75
76
77
78
# File 'lib/rmatrix/matrix.rb', line 71

def each_row(&block)
 e = Enumerator.new do |enum|
    (0...self.rows).each  do |i|
      enum << self.raw[i, true]
    end
  end
  block_given? ? e.each(&block) : e
end

#inspect(sz = 10, sig = 6) ⇒ Object



289
290
291
292
293
294
295
296
297
# File 'lib/rmatrix/matrix.rb', line 289

def inspect(sz=10, sig=6)
  return 'M[Empty]' if empty?
  return Vector::inspect_vector(self) if self.is_vector?
  values = condensed(10, sig, '', '', "")
  max_width = 0
  values = values.map{|line| line.map{|val| as_str = val.to_s; max_width = [as_str.length, max_width].max; as_str}}
  values = values.map{|line| line.map{|val| val.rjust(max_width, ' ') }}
  "#{rows} x #{columns} Matrix\nM[#{values.map{|row| "[#{row.join(", ")}]" }.join(",\n  ")}"
end

#is_vector?Boolean

Returns:

  • (Boolean)


278
279
280
# File 'lib/rmatrix/matrix.rb', line 278

def is_vector?
  [rows, columns].include?(1)
end

#join(other) ⇒ Object



173
174
175
176
177
178
179
180
181
182
# File 'lib/rmatrix/matrix.rb', line 173

def join(other)
  case true
  when self.rows == 1 && other.rows == 1
    Vector.new(NArray.to_na([self.narray,other.narray]).to_type(self.typecode).reshape(self.columns + other.columns, 1))
  when self.columns == 1 && other.columns == 1
    Vector.new(NArray.to_na([self.narray,other.narray]).to_type(self.typecode).reshape(1, self.rows + other.rows))
  else
    raise "Couldn't join mismatched dimensions"
  end
end

#maskObject



89
90
91
92
93
# File 'lib/rmatrix/matrix.rb', line 89

def mask
  mmap do |elm|
    (yield elm) ? 0 : elm
  end
end

#minor(x, y) ⇒ Object Also known as: M



216
217
218
# File 'lib/rmatrix/matrix.rb', line 216

def minor(x,y)
  return self.delete_at(y,x)
end

#mmapObject



80
81
82
83
84
85
86
87
# File 'lib/rmatrix/matrix.rb', line 80

def mmap
  as_na = NArray.to_na(
    matrix.each.map do |elm|
      yield elm
    end
  ).to_type(typecode)
  Matrix.new(as_na.reshape(*shape), typecode)
end

#mult(other) ⇒ Object



258
259
260
# File 'lib/rmatrix/matrix.rb', line 258

def mult(other)
  Matrix.new(self.narray * other.narray, typecode)
end

#round(dp) ⇒ Object



274
275
276
# File 'lib/rmatrix/matrix.rb', line 274

def round(dp)
  mmap{|x| x.round(dp) }
end

#rowsObject



108
109
110
# File 'lib/rmatrix/matrix.rb', line 108

def rows
  self.shape.last
end

#set_all(value) ⇒ Object



28
29
30
# File 'lib/rmatrix/matrix.rb', line 28

def set_all(value)
  narray[]=(value)
end

#sizeObject Also known as: length



104
105
106
# File 'lib/rmatrix/matrix.rb', line 104

def size
  self.shape.inject(:*).to_i
end

#sum(dim = nil) ⇒ Object



371
372
373
374
375
376
377
378
# File 'lib/rmatrix/matrix.rb', line 371

def sum(dim=nil)
  case dim
  when nil then
    res = self.narray.sum
    NArray === res ? Matrix.new(0, typecode)[0] : res
  else Matrix.new(self.matrix.sum(dim), typecode)
  end
end

#sum_columnsObject



134
135
136
# File 'lib/rmatrix/matrix.rb', line 134

def sum_columns
  sum(0)
end

#sum_rowsObject



130
131
132
# File 'lib/rmatrix/matrix.rb', line 130

def sum_rows
  sum(1)
end

#to_aObject



428
429
430
431
# File 'lib/rmatrix/matrix.rb', line 428

def to_a
  return narray.reshape(narray.length).to_a if is_vector?
  return narray.to_a
end

#to_mObject



437
438
439
# File 'lib/rmatrix/matrix.rb', line 437

def to_m
  self
end

#to_sObject



266
267
268
# File 'lib/rmatrix/matrix.rb', line 266

def to_s
  inspect
end

#to_significant_figures(x, p) ⇒ Object



282
283
284
285
286
287
# File 'lib/rmatrix/matrix.rb', line 282

def to_significant_figures(x, p)
  x.zero? ? 0 : begin
    nm = Math.log(x, 10.0).floor + 1.0 - p
    (((10.0 ** -nm) * x).round * (10.0 ** nm)).round(nm.abs)
  end
end

#to_tex(sz = 10, sig = 6) ⇒ Object



299
300
301
302
303
304
305
306
# File 'lib/rmatrix/matrix.rb', line 299

def to_tex(sz = 10, sig=6)
  values = condensed(sz, sig)
  <<-TEX
\\begin{pmatrix}
#{values.map{|line| line.join(" & ")}.join(" \\\\ ")}
\\end{pmatrix}
TEX
end

#to_type(type) ⇒ Object



380
381
382
# File 'lib/rmatrix/matrix.rb', line 380

def to_type(type)
  Matrix.new(narray.to_type(type), type)
end

#transposeObject Also known as: T



336
337
338
# File 'lib/rmatrix/matrix.rb', line 336

def transpose
  Matrix.new(self.matrix.transpose, typecode)
end

#two_dimensional(source, type) ⇒ Object



184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/rmatrix/matrix.rb', line 184

def two_dimensional(source, type)
  case source
  when NArray
    if NMatrix === source
      @matrix = source
      source = NArray.refer(source)
    end
  when Numeric
    source = NArray.to_na([source])
  else
    source = NArray.to_na(source)
    if type != RMatrix::Matrix::Typecode::OBJECT &&
      source.typecode == RMatrix::Matrix::Typecode::OBJECT &&
      RMatrix::Matrix === source[0]
      source = NArray.to_na(source.map(&:to_a).to_a).to_type(typecode)
    end
    source
  end

  source = source.to_type(type) unless type == source.typecode

  case source.dim
  when 1
    source.reshape(source.length, 1)
  when 2, 0
    source
  else
    raise "Source for matrix must be either one or two dimensional" unless source.shape[2..-1].all?{|x| x == 1}
    source.reshape(source.shape[0], source.shape[1])
  end
end

#zip(*others) ⇒ Object



354
355
356
# File 'lib/rmatrix/matrix.rb', line 354

def zip(*others)
  Matrix.new(super(*others), self.typecode)
end