How to Make a Matrix and Fill It With Random Numbers in Java

How to Make a Matrix and Fill It With Random Numbers in Java thumbnail
A matrix is a table of numbers, or a two-dimensional array in Java.

Java does not implement a Matrix class that provides built-in methods for manipulating matrices as one of its defaults. However, you can create and alter two-dimensional arrays of numbers as if they were matrices. In addition, the National Institute of Standards in Technology created a simple Matrix library in Java called JAMA, with which to create and manipulate matrices. You can use either method to create a matrix representation in Java, although without a special package you will need to implement matrix manipulations yourself.

Things You'll Need

  • JAMA package (optional)
Show More

Instructions

  1. Via Arrays

    • 1

      Create a 2D array of integers, e.g. "int [][] arr = new arr[x][y];", where "x" is the number of rows and "y" is the number of columns.

    • 2

      Create a new instance of a random number generator, e.g. "Random rand = new Random();"

    • 3

      Create a double for loop to loop through all matrix entries and add a new random number to each entry, such as: "for (int i = 0; i < x, i++) { for (int j = 0; j < y; j++) {arr[i][j] = rand.nextInt(r);} }", where "r" is the maximum value you want to generate.

    Via JAMA package

    • 4

      Download the JAMA package.

    • 5

      Include the JAMA matrix package in your project's dependencies, a process which depends on your JDK.

    • 6

      Create a new random matrix in your code by calling the static method Matrix.random(), e.g. "Matrix m = Matrix.random(x,y);" where x is the number of rows and y is the number of columns.

Tips & Warnings

  • Make sure to import the java.util.Random package to generate random numbers.

Related Searches:

References

  • Photo Credit Michael Blann/Digital Vision/Getty Images

Comments

Related Ads

Featured