2 - matrix
2 - matrix
A Matrix is a rectangular array. The elements are arranged in the rows and columns. In this
tutorial, we will look at some matrix programs in Java.
Matrix in Java
We can implement a matrix using two dimensional array in Java. The element at row “r” and
column “c” can be accessed using index “array[r][c]”.
1
int[][] first = new int[row][column];
int[][] second = new int[row][column];
System.out.println("Second Matrix:\n");
print2dArray(second);
// sum of matrices
sum(first, second);
}
System.out.println("\nSum of Matrices:\n");
print2dArray(sum);
}
2
}
System.out.println();
}
}
}
2. Subtracting Two Matrices
Here is the function to subtraction second matrix elements from the first matrix and then print
the result matrix.
private static void subtract(int[][] first, int[][] second) {
int row = first.length;
int column = first[0].length;
int[][] sum = new int[row][column];
System.out.println("\nSubtraction of Matrices:\n");
print2dArray(sum);
}
import java.util.Scanner;
3
int[][] matrix1 = new
int[rowsInFirst][colsInFirstRowsInSecond];
matrix1[i][j] = sc.nextInt();
matrix2[i][j] = sc.nextInt();
System.out.print(matrix1[i][j]+"\t");
4
}
System.out.println();
System.out.print(matrix2[i][j]+"\t");
System.out.println();
System.out.println("Product = ");
5
{
System.out.print(product[i][j]+"\t");
System.out.println();
4. Transpose Of A Matrix
Transpose of a matrix is formed by turning all rows of a matrix into columns and columns into rows.
import java.util.Scanner;
6
for (int j = 0; j < cols; j++)
{
System.out.print(matrix[i][j]+" ");
}
System.out.println();
}
System.out.println();
}
}
}
import java.lang.*;
class Matrixdet{
int i,j,k;
double sum=0;
if(m==1) { sum=b[0][0]; }
7
else if(m==2)
else
for(int p=0;p<m;p++)
int h=0;k=0;
for(i=1;i<m;i++)
for(j=0;j<m;j++)
if(j==p)
continue;
c[h][k]=b[i][j];
k++;
if(k==m-1)
h++;
k=0;
sum=sum+b[0][p]*Math.pow((-1),p)*determinent(c,m-1);
8
}
return sum;
System.out.println("\nMATRIX :");
int order=Integer.parseInt(in.readLine());
A[i][j] = Integer.parseInt(in.readLine());
System.out.println("MATRIX : ");
{ System.out.println();
System.out.print(A[i][j]+" ");
9
}
System.out.println();
10