Project

General

Profile

Feature #10073 ยป implementing_laplace_expansion.patch

gogotanaka (Kazuki Tanaka), 10/06/2014 02:33 AM

View differences:

lib/matrix.rb
60 60
# * #minor(*param)
61 61
# * #first_minor(row, column)
62 62
# * #cofactor(row, column)
63
# * #laplace_expansion(row_or_column: num)
64
# * #cofactor_expansion(row_or_column: num)
65
# * #cofact_exp(row_or_column: num)
63 66
#
64 67
# Properties of a matrix:
65 68
# * #diagonal?
......
636 639
    det_of_minor * (-1) ** (row + column)
637 640
  end
641
  #
642
  # Returns the laplace_expansion along +num+ -th +row_or_column+
643
  #
644
  #    Matrix[[Vector[1, 0], Vector[0, 1]], [2, 3]].laplace_expansion(row: 0)
645
  #     => Vector[3, -2]
646
  #
647
  #    Matrix[[7,6], [3,9]].laplace_expansion(column: 1)
648
  #     => 45
649
  #
650
  def laplace_expansion(row: nil, column: nil)
651
    Matrix.Raise ErrDimensionMismatch unless square?
652
    raise RuntimeError, "laplace_expansion of empty matrix is not defined" if empty?
653

  
654
    num = row || column
655

  
656
    if !num || (row && column)
657
      raise ArgumentError, "should be hash which has either :row or :column as key"
658
    end
659

  
660
    unless 0 <= num && num < row_count
661
      raise ArgumentError, "invalid num (#{num.inspect} for 0..#{row_count - 1})"
662
    end
663

  
664
    send(row ? :row : :column, num).map.with_index { |e, k|
665
      e * cofactor(*(row ? [num, k] : [k,num]))
666
    }.inject(:+)
667
  end
668
  alias_method :cofactor_expansion, :laplace_expansion
669
  alias_method :cofact_exp, :laplace_expansion
670

  
638 671
  #--
639 672
  # TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
640 673
  #++