2. Matrices In this exercise you will write several functions that operate on ma
ID: 3729007 • Letter: 2
Question
2. Matrices In this exercise you will write several functions that operate on matrices or two-dimensional arrays. For this exercise, we will restrict our attention to square matrices collections of numbers with the same number of columns and rows. You will place all the function prototypes in a header file named matrix_utils.h with their definitions in a source file named matrix_utils.c. You should test your functions by writing a driver program, but you need not handitn (a) Write a function that constructs a new n × n identity matrix. An identity matrix is a square matrix with ones on the diagonal and zeros everywhere else. int **getIdentityMatrix(int n); b) Write a function that takes two matrices and determines if they are equal (all of their elements are the same). int isEqual(int **A, int **B, int n); c) Write a function that takes a matrix and an index i and returns a new array thatExplanation / Answer
If you post more than 4 parts in a question, as per chegg guidelines I have to solve only 4 parts.
(A)
int **getIdentityMatrix(int n)
{
// dynamically allocate memory for n x n matrix
int **arr = (int **)malloc( n * sizeof(int *) );
int i, j;
for( i = 0 ; i < n ; i++ )
arr[i] = (int *)malloc( n * sizeof(int) );
// initialize array with 0
for( i = 0 ; i < n ; i++ )
for( j = 0 ; j < n ; j++ )
arr[i][j] = 0;
// set the disgonal values to 1
for( i = 0 ; i < n ; i++ )
arr[i][i] = 1;
return arr;
}
(b)
int isEqual( int **A, int **B, int n )
{
int i, j;
// traverse the row
for( i = 0 ; i < n ; i++ )
// traverse the column
for( j = 0 ; j < n ; j++ )
// if the current (i, j) element of the two matrix are not equal
if( A[i][j] != B[i][j] )
return 0;
// if the matrix are equal
return 1;
}
(c)
int *getRow(int **A, int n, int i)
{
int *arr = (int *)malloc( n * sizeof(int) );
int j;
for( j = 0 ; j < n ; j++ )
arr[j] = A[i][j];
return arr;
}
(d)
int *getCol(int **A, int n, int j)
{
int *arr = (int *)malloc( n * sizeof(int) );
int i;
for( i = 0 ; i < n ; i++ )
arr[i] = A[i][j];
return arr;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.