domingo, 3 de agosto de 2008

Cálculo com matrizes

Ando fazendo uma revisão em álgebra linear e comecei a criar uma classe para fazer cálculos básicos com matrizes, para auxiliar em cálculos mais complexos posteriormente.

Abaixo segue a classe Matrix.



package br.lalgebra.math.matrix;

import br.lalgebra.math.errors.MatrixError;

public class Matrix
{

/**
* figure out the product between a factor and a matrix
* @param f
* @param A
* @return
* @throws MatrixError
*/
public static double[][] productNumber( double f, double A[][] ) throws MatrixError
{
double r[][] = null;

if (A.length == 0)
throw new MatrixError("There is some empty matrix");

// matrix A (mxn)
int m = A.length; int n = A[0].length;

r = new double[m][n];

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
r[i][j] = f * A[i][j];
}

return r;
}

/**
* figure out the matrix product
* @param A
* @param B
* @return
*/
public static double[][] product( double A[][], double B[][] ) throws MatrixError
{

double r[][] = null;

if (A.length == 0 || B.length == 0)
throw new MatrixError("There is some empty matrix");

// matrix A (mxn)
int m = A.length; int n = A[0].length;

// matrix B (pxq)
int p = B.length; int q = B[0].length;

if (n != p)
throw new MatrixError("The number of columns of matrix A, must be the same of matrix B number of rows");

double aux = 0.0;

// defining the new array
r = new double[m][q];

// figuring out arrays product
for (int i = 0; i < m; i++)
for (int k = 0; k < q; k++)
{
for (int j = 0; j < n; j++)
aux += A[i][j] * B[j][k];
r[i][k] = aux;
aux = 0;
}

return r;
}

public static String getString( double[][] x ) throws MatrixError
{
String result = "";

if (x.length == 0)
throw new MatrixError("The matrix is empty");

int m = x.length; int n = x[0].length;

if (n == 0)
throw new MatrixError("The matrix is empty");

for (int i = 0; i < m; i++) {
for (int j =0; j < n; j++)
result += x[i][j] + "\t";
result += "\n";
}
return result;
}
}

Nenhum comentário:

Postar um comentário