0

I'm new to java and am trying to find the transpose of a matrix X with m rows and x columns. I'm not familiar with java syntax but I think I can access the number of rows using double[x.length] but how do I figure out the number of columns? Here is my code:

import stdlib.StdArrayIO;

public class Transpose {
    // Entry point
    public static void main(String[] args) {
        double[][] x = StdArrayIO.readDouble2D();
        StdArrayIO.print(transpose(x));
    }

    // Returns a new matrix that is the transpose of x.
    private static double[][] transpose(double[][] x) {
        // Create a new 2D matrix t (for transpose) with dimensions n x m, where m x n are the
        // dimensions of x.
        double[][] t = new double[x.length][x[1.length]]

        // For each 0 <= i < m and 0 <= j < n, set t[j][i] to x[i][j].
        


        // Return t.
    


    }
}

Also, I was trying to figure it out by printing a 2D list in a scrap file but It wouldn't work for some reason, where is what I had:

import stdlib.StdArrayIO;
import stdlib.StdOut;

public class scrap {
    public static void main(String[] args){
        double[][] x = new double[10][20];
        StdOut.println(x.length);
    }


}

Could you point out what I was doing wrong? It kept waiting on input. I could also use any other tips that would help, I am transitioning from Python.

1
  • 1
    x[1.length] -> x[1].length Commented Feb 5, 2023 at 6:31

1 Answer 1

2

In Java, a two-dimensional array is merely an array of arrays. This means the length of any of the array elements can be checked to find the number of columns. Using your example, this would be:

double[][] t = new double[x[0].length][x.length];

This should be sufficient for your matrix situation, where we can assume the outer array is not empty, and all inner arrays have the same length.

Note that this is not guaranteed to work in general. If the outer array is empty, there are no inner arrays to check, so the number of columns isn't defined and can't be determined. Secondly, there is no guarantee that all inner arrays of a given array of arrays in Java are all the same length. They will be using the new double[x][y] syntax, but the array could have been created using another mechanism or one of the inner arrays could have been replaced with an array of a different length.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.