How to get the transpose of a matrix/array in java?

Assume I have a matrix A.What do I have to type to get the transposed matrix of A? (lets say B)

(I have imported Apache Commons Math in my project and I want to do it using these libraries)

My code is:

double[][] A = new double[2][2];
        A[0][0] = 1.5;
        A[0][1] = -2.0;
        A[1][0] = 7.3;
        A[1][1] = -13.5;

Then,what?...

(I have found this link, but I don't know what exactly to do:

http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/linear/RealMatrix.html

I have tried :

double[][] a = new double[2][2];
a = RealMatrix.transpose();

Also,

double[][] a = new double[2][2];
a = A.transpose();

And how can I transpose an array a in the same way?

Upvotes: 0

Views: 7496

Answers (2)

The_Lost_Avatar
The_Lost_Avatar

Reputation: 990

double[][] matrixData = { {1.5d,2d}, {7.3d,-13.5d}};
RealMatrix m = MatrixUtils.createRealMatrix(matrixData);

There is a method called transpose that returns the transpose of the matrix

RealMatrix m1=m.transpose();

m1 would be the transpose of m

Upvotes: 1

Vivek
Vivek

Reputation: 920

You can try something like:

public void transpose() {

        final int[][] original = new int[][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
        for (int i = 0; i < original.length; i++) {
            for (int j = 0; j < original[i].length; j++) {
                System.out.print(original[i][j] + " ");
            }
            System.out.print("\n");
        }
        System.out.print("\n\n matrix transpose:\n");
        // transpose
        if (original.length > 0) {
            for (int i = 0; i < original[0].length; i++) {
                for (int j = 0; j < original.length; j++) {
                    System.out.print(original[j][i] + " ");
                }
                System.out.print("\n");
            }
        }
    }

Upvotes: 1

Related Questions