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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With