Here's a full Java code example that demonstrates matrix multiplication using the Apache Commons Math library. This example includes a class named BAexp as per your request.
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.RealMatrix;
/**
* This class demonstrates matrix multiplication.
*/
public class BAexp {
public static void main(String[] args) {
// Define two matrices
double[][] matrixAData = {{1, 2}, {3, 4}};
double[][] matrixBData = {{5, 6}, {7, 8}};
// Create RealMatrix instances
RealMatrix matrixA = new Array2DRowRealMatrix(matrixAData);
RealMatrix matrixB = new Array2DRowRealMatrix(matrixBData);
// Perform matrix multiplication
RealMatrix matrixMatrixProduct = matrixB.multiply(matrixA);
// Print the result
System.out.println("Matrix A:");
printMatrix(matrixA);
System.out.println("Matrix B:");
printMatrix(matrixB);
System.out.println("Matrix B * Matrix A:");
printMatrix(matrixMatrixProduct);
}
/**
* Prints a matrix to the console.
*
* @param matrix the matrix to print
*/
private static void printMatrix(RealMatrix matrix) {
for (int i = 0; i < matrix.getRowDimension(); i++) {
for (int j = 0; j < matrix.getColumnDimension(); j++) {
System.out.print(matrix.getEntry(i, j) + " ");
}
System.out.println();
}
}
}
To compile and run this code, ensure you have the Apache Commons Math library in your classpath. If you're using Maven, add the following dependency to your pom.xml:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
This code defines two matrices A and B, performs the matrix multiplication B * A, and prints the result. The printMatrix method is a helper function to display the matrices in a readable format.