Reputation: 110
Does anyone know how to construct following matrix in Java?
I can see a transpose pattern but I might be on the wrong track with that. This is what I've got so far... don't laugh :-)
import java.io.*;
public class Diagonal
{
public static void main(String[] args)throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
int dim;
do
{
System.out.print("Dimension: ");
dim = Integer.parseInt(in.readLine());
}while(dim<=0);
int[][] matrix = new int[dim][dim];
for(int i=0;i<matrix.length;i++)
{
for(int j=0;j<matrix[i].length;j++)
{
matrix[i][j] = j+1;
}
}
//Transpose
int transpose[][] = matrix;
for(int i=0;i<dim;i++)
{
for(int j=0;j<dim;j++)
{
transpose[j][i] = matrix[i][j];
}
}
//print transpose
for(int i=0;i<transpose.length;i++)
{
for(int j=0;j<transpose[i].length;j++)
{
System.out.print(transpose[i][j]);
}
System.out.println("");
}
}
}
I'm not sure but I think it is called a toeplitz matrix...
Grts.
Upvotes: 2
Views: 4624
Reputation: 1372
public static void createMatrix(int no) {
int front = 1, last = no, position = 0;
for (int i = 0; i < no; i++) {
for (int j = front; j > 0; j--) {
System.out.print(j);
}
for (int j = 2; j <= last; j++) {
System.out.print(j);
}
front++;
last--;
}
}
output:
This function return a array like below
1, 2, 3, 4, 5, 6, 7, 8
2, 1, 2, 3, 4, 5, 6, 7
3, 2, 1, 2, 3, 4, 5, 6
4, 3, 2, 1, 2, 3, 4, 5
5, 4, 3, 2, 1, 2, 3, 4
6, 5, 4, 3, 2, 1, 2, 3
7, 6, 5, 4, 3, 2, 1, 2
8, 7, 6, 5, 4, 3, 2, 1
Upvotes: 0
Reputation: 907
A Toeplitz matrix implies that all diagonals in a given matrix are constants. Your matrix is a special type of Toeplitz matrix which is transpose-able. M == MT. Check out Circulant Matrices as well...
Notice that you are trying to find a matrix, where all values correspond to the distance (if you will) between i and j. Hence something like this will work:
int[][] matrix = new int[dim][dim];
for(int i=0;i<matrix.length;i++)
{
for(int j=0;j<matrix.length;j++)
{
// Figure out distance from i -> j
matrix[i][j] = Math.abs(i - j) + 1;
}
}
Upvotes: 2
Reputation: 328629
Note that: m[i][j] = Math.abs(i - j) + 1
. Once you have seen that, creating the matrix is fairly simple:
private static int[][] createMatrix(int n) {
int[][] m = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
m[i][j] = Math.abs(i - j) + 1;
}
}
return m;
}
And you can try it out:
public static void main(String[] args) {
for (int[] row : createMatrix(8)) {
System.out.println(Arrays.toString(row));
}
}
prints:
[1, 2, 3, 4, 5, 6, 7, 8]
[2, 1, 2, 3, 4, 5, 6, 7]
[3, 2, 1, 2, 3, 4, 5, 6]
[4, 3, 2, 1, 2, 3, 4, 5]
[5, 4, 3, 2, 1, 2, 3, 4]
[6, 5, 4, 3, 2, 1, 2, 3]
[7, 6, 5, 4, 3, 2, 1, 2]
[8, 7, 6, 5, 4, 3, 2, 1]
Upvotes: 5