Reputation: 13296
I have to create a method to multiply a given Matrix by its transpose.
Consider my matrix is 2d array double [][] matrix;
public double[][] MultiplyByTranspose(double[][] matrix)
{
return newMatrix;
}
If you need my Matrix class check it in the answer of this question
Upvotes: 1
Views: 5408
Reputation: 186803
Well, the simplest way is just to implement Transpose and Multiplication.
Of course, when combined, it could be done more efficient, but I think that you'll need Transpose and Multiplication as separated routine further in your code (you've asked about matrix rotation)
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);
}
Upvotes: 2