Convert a Matrix into another Matrix of given dimensions | Java program to implement the above approach ; Function to cona matrix of size A * B from the given matrix elements ; Initialize a new matrix ; Traverse the matrix , mat [ ] [ ] ; Update idx ; Print the resultant matrix ; Driver Code
import java . util . * ; class GFG { static void ConstMatrix ( int [ ] [ ] mat , int N , int M , int A , int B ) { if ( N * M != A * B ) return ; int idx = 0 ; int [ ] [ ] res = new int [ A ] [ B ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { res [ idx / B ] [ idx % B ] = mat [ i ] [ j ] ; idx ++ ; } } for ( int i = 0 ; i < A ; i ++ ) { for ( int j = 0 ; j < B ; j ++ ) System . out . print ( res [ i ] [ j ] + " ▁ " ) ; System . out . print ( "NEW_LINE"); } } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 1 , 2 , 3 , 4 , 5 , 6 } } ; int A = 2 ; int B = 3 ; int N = mat . length ; int M = mat [ 0 ] . length ; ConstMatrix ( mat , N , M , A , B ) ; } }