Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent a 2D matrix in Java?

I have to create in Java a 2D matrix (consisting of double values) as well as a 1D vector. It should be possible to access individual rows and columns as well as individual elements. Moreover, it should be thread-safe (threads writing at the same time). Perhaps later I need some matrix operations too.

Which data structure is best for this? Just a 2D array or a TreeMap? Or is there any amazing external library?

like image 985
machinery Avatar asked Feb 06 '16 10:02

machinery


People also ask

How do you represent a matrix in Java?

Fig 1: A simple 4x4 matrix In order to represent this matrix in Java, we can use a 2 Dimensional Array. A 2D Array takes 2 dimensions, one for the row and one for the column. For example, if you specify an integer array int arr[4][4] then it means the matrix will have 4 rows and 4 columns.

How do you instantiate a 2D array in Java?

On the other hand, to initialize a 2D array, you just need two nested loops. 6) In a two dimensional array like int[][] numbers = new int[3][2], there are three rows and two columns. You can also visualize it like a 3 integer arrays of length 2. You can find the number of rows using numbers.


3 Answers

If you need thread safe behavior, use

Vector<Vector<Double>> matrix = new Vector<Vector<Double>>();

If you don't need thread safe behavior, use

ArrayList<ArrayList<Double>> matrix = new ArrayList<ArrayList<Double>>();
like image 94
Aniket Rangrej Avatar answered Oct 29 '22 01:10

Aniket Rangrej


I'll give you an example:

int rowLen = 10, colLen = 20;   
Integer[][] matrix = new Integer[rowLen][colLen];
for(int i = 0; i < rowLen; i++)
    for(int j = 0; j < colLen; j++)
        matrix[i][j] = 2*(i + j); // only an example of how to access it. you can do here whatever you want.

Clear?

like image 26
Paulo Avatar answered Oct 29 '22 01:10

Paulo


You should use Vector for 2D array. It is threadsafe.

Vector<Vector<Double>>  matrix= new Vector<Vector<Double>>();

    for(int i=0;i<2;i++){
        Vector<Double> r=new Vector<>();
        for(int j=0;j<2;j++){
            r.add(Math.random());
        }
        matrix.add(r);
    }
    for(int i=0;i<2;i++){
        Vector<Double> r=matrix.get(i);
        for(int j=0;j<2;j++){
            System.out.print(r.get(j));
        }
        System.out.println();
    }

If this is your matrix indexes

00 01

10 11

You can get specifix index value like this

Double r2c1=matrix.get(1).get(0); //2nd row 1st column

Have a look at Vector

like image 10
Noor Nawaz Avatar answered Oct 29 '22 01:10

Noor Nawaz