Method: AppMath::Mat#initialize

Defined in:
lib/linalg.rb

#initialize(*arg) ⇒ Mat

These are the 5 mehods to generate a matrix via ‘new’

m1 = Mat.new(aMat)
m2 = Mat.new(anArrayOfVec)
m3 = Mat.new(aVec)
m4 = Mat.new(aPositiveInteger, aRealOrComplex)
m5 = Mat.new(aPositiveInteger, aPositiveInteger, aRealOrComplex)

Here, m1 is a copy of aMat, m2 is a matrix which has as row vectors, the components of anArrayOfVec. If these vectors have not all he same dimension, failure results; m3 is a square matrix in which only the main diagonal may have non-zero elements, and in which ths diagonal is given as aVec; m4 is a square matrix with the dimension given by the first argument, and with all matrix elements equal to the second argment; m5 is a rectangular matrix with dim1 and dim2 given by the first and the second argument, and with all matrix elements equal to the third argument.



429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
# File 'lib/linalg.rb', line 429

def initialize(*arg)
  case arg.size
  when 0
    @x = Array.new
  when 1 # ok if this is a Matrix or an array of Vectors
    a0 = arg[0]
    if a0.is_a?(Mat)
      @x = Array.new(a0.x)
    elsif a0.is_a?(Array)
      n = a0.size
      if n.zero?
        @x = Array.new
      else
        misfit = 0
        a0.each{|c|
          misfit += 1 unless c.is_a?(Vec)
        }
        fail "input must consist of Vec-objects" unless misfit.zero?
        misfit2 = 0
        d2 = a0[1].dim
        a0.each{|c|
          misfit2 += 1 unless c.dim == d2
        }
        fail "input Vec-objects must agree in dimension" unless 
          misfit.zero?
        @x = a0.clone
      end
    elsif a0.is_a?(Vec) # make a diagonal matrix
      n = a0.dim
      if n.zero?
        @x = Array.new
      else
        c = a0[1].to_0
        vc = Vec.new(n,c)
        @x = Array.new(n,vc)
        for i in 1..n
          s!(i,i,a0[i])
        end
      end
    else
      fail "no reasonable construction available for this argument"
    end
  when 2 # make a square matrix, the diagonal filled with one element
    # (all others zero)
    n = arg[0]
    a = arg[1]
    zero = a.to_0
    vc = Vec.new(n,zero)
    @x = Array.new(n,vc)
    for i in 1..n
      vi = Vec.new(vc)
      vi[i] = a
      @x[i-1] = vi
    end
  when 3 # make rectangular matrix filled with one element
    n1 = arg[0]
    fail "first argument must be integer" unless n1.integer?
    n2 = arg[1]
    fail "second argument must be integer" unless n2.integer?
    a = arg[2]
    vc = Vec.new(n2,a)
    @x = Array.new(n1,vc)
  else
    fail "no construction for more than 3 arguments"
  end
end