Takes the transpose of an array (like the matrix operation). - Java java.lang

Java examples for java.lang:Math Matrix

Description

Takes the transpose of an array (like the matrix operation).

Demo Code


//package com.java2s;

public class Main {
    /**/*from w w w .  ja va2  s.c o  m*/
     * Takes the transpose of an array (like the matrix operation).
     *
     * @throws IllegalArgumentException if the array is not a matrix
     */
    public static double[][] transpose(double[][] M) {
        double[][] Mt = new double[M[0].length][M.length];
        for (int i = 0; i < M.length; i++) {
            if (M[i].length != M[0].length) {
                throw new IllegalArgumentException(
                        "The array is not a matrix.");
            }
            for (int j = 0; j < M[0].length; j++) {
                Mt[j][i] = M[i][j];
            }
        }
        return (Mt);
    }

    /**
     * Takes the transpose of an array (like the matrix
     * operation).
     *
     * @throws IllegalArgumentException if the array
     *                                  is not a matrix
     */
    public static int[][] transpose(int[][] M) {
        int[][] Mt = new int[M[0].length][M.length];
        for (int i = 0; i < M.length; i++) {
            if (M[i].length != M[0].length) {
                throw new IllegalArgumentException(
                        "The array is not a matrix.");
            }
            for (int j = 0; j < M[0].length; j++) {
                Mt[j][i] = M[i][j];
            }
        }
        return (Mt);
    }
}

Related Tutorials