Matrix_Operations.java Source code

Java tutorial

Introduction

Here is the source code for Matrix_Operations.java

Source

import java.util.Scanner;
import org.apache.commons.math3.linear.LUDecomposition;
import org.apache.commons.math3.linear.MatrixUtils;
import org.apache.commons.math3.linear.RealMatrix;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 * @author newuser
 */
public class Matrix_Operations {

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        //Allow user to enter number of columns
        int rows = getRowsNumberFromUser();
        int columns = getColumnNumberFromUser();
        double matrixA[][] = new double[rows][columns];

        //Enter values for matrix
        System.out.println("Enter values for each position in the matrix below. ");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                matrixA[i][j] = keyboard.nextDouble();

            }
            System.out.println("");
        }

        showMatrix(matrixA);
        System.out.println("");
        RealMatrix A = MatrixUtils.createRealMatrix(matrixA);

        LUDecomposition lu = new LUDecomposition(A);

        showMatrix(matrixA);

        System.out.println(lu.getDeterminant());

    }

    public static void showMatrix(double[][] array) {
        for (double[] ds : array) {
            for (double d : ds) {
                System.out.print(d + "\t");
            }
            System.out.println("");
        }
    }

    public static int getRowsNumberFromUser() {
        Scanner keyboard = new Scanner(System.in);
        //Allow user to enter number of rows
        int rows;
        System.out.print("Enter rows: ");

        rows = keyboard.nextInt();
        return rows;

    }

    public static int getColumnNumberFromUser() {
        Scanner keyboard = new Scanner(System.in);
        //Allow user to enter number of columns
        int columns;
        System.out.print("Enter columns: ");

        columns = keyboard.nextInt();

        return columns;

    }
}