How to Make a Matrix and Fill It With Random Numbers 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.
Instructions
-
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.
-
1
Tips & Warnings
Make sure to import the java.util.Random package to generate random numbers.
References
- Photo Credit Michael Blann/Digital Vision/Getty Images