简体   繁体   中英

How to return a transposed matrix in a different class?

I have my main class which asks to transpose my pre-existing matrix. I got the idea, but I can't return Matrix object. Gives an error of Type Mismatch - cannot convert from int[][] to matrix .

    public class Matrix {
    int numRows;
    int numColumns;
    int data[][];

    public Matrix transpose() {
    int[][] M = new int [numColumns][numRows];
    for (int i = 0; i < numRows; i++) {
        for (int j = 0; j < numColumns; j++) {
            M[j][i] = data[i][j];
        }
    }
    return M;
}

You have two options.

Option 1 (Change Return Type):

Options 1 is to change return type from Matrix to int[][] .

public int[][] transpose() {
    int[][] M = new int[numColumns][numRows];
    for (int i = 0; i < numRows; i++) {
        for (int j = 0; j < numColumns; j++) {
            M[j][i] = data[i][j];
        }
    }
    return M;
}

Option 2 (Create an object and return it):

Your Option 2 is to create an object and add transposed matrix to that object and return it.

public Matrix transpose() {
    int[][] M = new int[numColumns][numRows];
    for (int i = 0; i < numRows; i++) {
        for (int j = 0; j < numColumns; j++) {
            M[j][i] = data[i][j];
        }
    }
    return new Matrix(numColumns, numRows, M);
}

Assuming your constructor looks like this

public Matrix(int numRows, int numColumns, int[][] data) {
    this.numRows = numRows;
    this.numColumns = numColumns;
    this.data = data;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM