Question

This is how I currently solve the problem of adding elements on the array's diagonal. I've tried a few other ways and I'm not satisfied. I'm sure there should be a smarter alternative to using the double loop and if statement. Any suggestions are welcome.

public SampleClass(){

    private static int nDims = 5;


    public static void main(String args[]){
          identityMatrix(nDims);

     }



    public double[][] identityMatrix(int input1dims){
            int nDims = input1dims;
            double[][] IM = new double[nDims][nDims];
            for (int i=0;i<nDims;i++){
                for (int j=0;j<nDims;j++){
                    if (i==j){
                        IM[i][j]=1;
                    }
                }
            }
            return IM;
   }
}
Était-ce utile?

La solution

You only do something if i == j. That should tell you that you only need one of those variables. In fact, you only need one of the loops, because you're only doing nDims operations.

for (int i=0;i<nDims;i++){
    IM[i][i] = 1;
}

Autres conseils

For a simple diagonal you can use a single variable:

for (int i = 0; i < nDims; i++) {
    IM[i][i] = 1;
}

But if you want an offset diagonal you can do this:

for (int i = 0; j = 1; i < nDims && j < nDims; i++, j++) {
    IM[i][j] = 1;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top