Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating N by N diagonal matrix using basic logic

I want to create a matrix of size N by N where N is a constant value defined globally, for now I just want to create a matrix where N=6. Where I fall short is I want to make it diagonally, like so:

0 1 2 3 4 5
1 0 1 2 3 4
2 1 0 1 2 3
3 2 1 0 1 2
4 3 2 1 0 1
5 4 3 2 1 0

Currently I have this method:

public static void drawMatrix(){
    for (int line = 0; line < N; line++){
        for (int j = 0; j < N; j++){
            System.out.print(j + " ");
        }
        System.out.println();
    }
}

Unfortunately it's only able to print 0 1 2 3 4 5 in every line, so I suppose I need another nested for-loop, however I'm not sure how to set it up.

like image 238
UndyingJellyfish Avatar asked Sep 07 '16 11:09

UndyingJellyfish


People also ask

How do you make a diagonal matrix?

The most common and easiest way to create a diagonal matrix is using the built-in function diag. The expression diag (v) , with v a vector, will create a square diagonal matrix with elements on the main diagonal given by the elements of v , and size equal to the length of v .

How do you convert a vector to a diagonal matrix?

D = diag( v ) returns a square diagonal matrix with the elements of vector v on the main diagonal. D = diag( v , k ) places the elements of vector v on the k th diagonal. k=0 represents the main diagonal, k>0 is above the main diagonal, and k<0 is below the main diagonal.


1 Answers

j is the column number, so it will be the same for all rows. What you need to do is to add or subtract j from the line number, depending on the line number, in order to make a "shift". Since the result could become negative, you will need to add N and mod by N:

if (j > line) {
    System.out.print((N-line+j)%N + " ");
} else {
    System.out.print((line-j+N)%N + " ");
}

Demo.

You can also rewrite it without an if using a conditional expression:

int sign = j > line ? -1 : 1;
System.out.print((N+sign*(line-j))%N + " ");

Demo.

like image 72
Sergey Kalinichenko Avatar answered Sep 25 '22 21:09

Sergey Kalinichenko