如何通过其转置乘以给定的矩阵?

时间:2014-01-09 11:15:15

标签: c# matrix transpose

我必须创建一个方法,将给定的Matrix乘以它的转置。

enter image description here

考虑我的矩阵是2d数组double [][] matrix;

public double[][] MultiplyByTranspose(double[][] matrix) 
{  
    return newMatrix;
}

如果您需要我的Matrix课程,请在answer of this question

中查看

1 个答案:

答案 0 :(得分:1)

嗯,最简单的方法就是实现 Transpose and Multiplication。

当然,当组合时,它可以更高效,但我认为你需要Transpose和Multiplication作为分离的例程进一步在您的代码中(您已经询问矩阵旋转

public static Boolean IsRectangle(Double[][] value) {
  if (Object.ReferenceEquals(null, value))
    return false;
  else if (value.Length <= 0)
    return false;

  Double[] line = value[value.Length - 1];

  if (Object.ReferenceEquals(null, line))
    return false;

  int size = line.Length;

  for (int i = value.Length - 2; i >= 0; --i)
    if (Object.ReferenceEquals(null, value[i]))
      return false;
    else if (value[i].Length != size)
      return false;

  return true;
}

public static Double[][] Transpose(Double[][] value) {
  if (Object.ReferenceEquals(null, value))
    throw new ArgumentNullException("value");

  if (!IsRectangle(value))
    throw new ArgumentException("value should be a rectangular matrix.", "value");

  int colCount = value.Length;
  int rowCount = value[value.Length - 1].Length;

  Double[][] result = new Double[rowCount][];

  for (int i = rowCount - 1; i >= 0; --i) {
    Double[] line = new Double[colCount];
    result[i] = line;

    for (int j = colCount - 1; j >= 0; --j)
      line[j] = value[j][i];
  }

  return result;
}

// Simple quibic algorithm
public static Double[][] Multiply(Double[][] left, Double[][] right) {
  if (Object.ReferenceEquals(null, left))
    throw new ArgumentNullException("left");
  else if (Object.ReferenceEquals(null, right))
    throw new ArgumentNullException("right");

  if (!IsRectangle(left))
    throw new ArgumentException("left should be a rectangular matrix", "left");
  else if (!IsRectangle(right))
    throw new ArgumentException("right should be a rectangular matrix", "right");

  int leftRows = left.Length;
  int leftCols = left[0].Length;

  int rightRows = right.Length;
  int rightCols = right[0].Length;

  if (leftCols != rightRows)
    throw new ArgumentOutOfRangeException("right");

  Double[][] result = new Double[leftRows][];

  for (int r = leftRows - 1; r >= 0; --r) {
    Double[] leftLine = left[r];
    Double[] line = new Double[rightCols];
    result[r] = line;

    for (int c = rightCols - 1; c >= 0; --c) {
      Double s = 0.0;

      for (int i = leftCols - 1; i >= 0; --i)
        s += leftLine[i] * right[i][c];

      line[c] = s;
    }
  }

  return result;
}

...

public double[][] MultiplyByTranspose(double[][] matrix) {  
  //TODO: Check the order! Which matrix should be the first and which the second,
  // In Linear Algebra A * B != B * A 
  return Multiply(matrix, Transpose(matrix));
  // Or 
  // return Multiply(Transpose(matrix), matrix);
}