Problem Solving: Matrices with 2-D Arrays

Learn how multi-dimensional arrays can be used in different operations.

Column-by column sum

Given a two-dimensional array, calculate the sum of each column.

Sample input

4 3 2 1 5
5 2 5 4 6
1 2 3 5 7
8 9 6 3 2
1 3 5 7 9

Sample output

[19,19,21,20,29]

Let’s discuss how we can solve this problem.

First, let’s make a function sumofAColumn() in which we have three parameters:

  • int M[][maxCols]: The 2-D array that needs to be processed.
  • int ci: The column index ci.
  • int rows: The total number of rows in M.

To calculate the sum of the cith column we need to fix the column to ci and iterate each row from 0 to rows-1. We will accumulate each value and return the accumulated sum at the end.

Press + to interact
int sumOfAColumn(const int M[][maxCols], int ci, int rows)
{
int sum = 0;
for (int r = 0; r < rows; r++) // iterating through every row
{
sum += M[r][ci]; // the column is fixed to ci
}
return sum; // returning the accumulation
}
int main() {
int arr[2][2] = {{1, 2}, {3, 4}};
print2DArray("2x2 Matrix:", arr, 2, 2);
cout << "\nSum of column 0: " << sumOfAColumn(arr, 0, 2) << endl;
return 0;
}

Now, we want to calculate the sum of all the columns. How can we do that? We will use the function sumOfAllColumns() with the following parameters:

  • int M[][maxCols]: where all the values are stored.
  • int rows: The total number of rows that need to be processed.
  • int cols: The total number of columns that need to be processed.
  • int colsSum[]: Where each column’s is stored.
  • int &sumSize: The number of answers calculated.

In this function, we will iterate through each column and calculate the summation of each column by calling sumOfAColumn() and storing it one by one in the colsSum[] array.

Let’s write it down:

Press + to interact
void sumOfAllColumns(int M[][MaxCols], int rows, int cols, int colsSum[], int &sumSize)
{
for (int c = 0; c < cols; c++) // for each column
{
colsSum[c] = sumOfAColumn(M, c, rows); // calculating the summation of c'th column
// and storing it
}
sumSize=cols; // cols many columns summations were computed
}

Here is the playground containing the complete code.

5 5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Column by column sum

Transpose of a square matrix

Write a program that does the following:

  1. Read a matrix from the file.
  2. Print it on screen.
  3. Transpose the matrix.
  4. Display the transposed matrix on the console screen.

Sample input

Matrix:
                  4  3  2  1  5
                  5  2  5  4  6
                  1  2  3  5  7
                  8  9  6  3  2
                  1  3  5  7  9

Transpose of Matrix:
                  4  5  1  8  1
                  3  2  2  9  3
                  2  5  3  6  5
                  1  4  5  3  7
                  5  6  7  2  9

Let’s make a function transposeOfMatrix() in which we will swap each (i,j)(i,j)th value of the matrix with (j,i)(j,i). For example, the value of row (0,1) will be swapped with (1,0) and that of (0,2) will be swapped with (2,0) and so on.

Look at the animation below:

We need to be careful to run the swapping with either the upper half of the matrix or the lower half but not both.

What will happen if we do the swapping on each (i,j)(i,j) index? Think about it! We will discuss the answer in the quiz that follows a little later.

Look at the code below:

Press + to interact
void transposeOfMatrix(int M[][maxCols], int &rows, int &cols)
{
for (int r = 0; r < rows; r++)
{
for(int c=r+1; c< cols; c++) // The inner loop makes sure to work for upper half only
swap(M[r][c], M[c][r]);
}
if(rows!= cols)
swap(rows, cols); // swapping the dimension
}

Let’s execute the complete code below:

5 5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Transpose of matrix

We have a question for you:

Find the logical error.

Question

What if we change the inner loop with this:

        for(int c=0; c< cols; c++)

In the above, c=0. Is this the correct function? Copy and debug this function in the above playground and see what will be the output of this function.

void transposeOfMatrix(int M[][maxCols], int &rows, int &cols)
{
    for (int r = 0; r < rows; r++)
    {
        for(int c=0; c< cols; c++)
            swap(M[r][c], M[c][r]);
    }
    if(rows!= cols)
        swap(rows, cols);
}
Show Answer

Identity matrix or not

Write a program that does the following:

  1. Load the matrix.
  2. Print the matrix.
  3. Print whether the matrix is an identity matrix or not.

What’s an identity matrix?

That identity matrix is a square matrix with all 1s placed diagonally and all 0s placed off the diagonal.

For example:

Identity matrix 3x3:
1 0 0
0 1 0
0 0 1

Let’s make a function isIdentityMatrix() that should receive a matrix and its dimension as input and return true if the matrix is an identity matrix and false otherwise.

Implementation details

  • First, we will compare rows with cols to check whether the matrix is square. If a matrix is not square, we’ll return false.

  • We will iterate through every index and check the following:

    • If the index is non-diagonal and the value is non-zero, return false.
    • If the index is a diagonal entry and the value is not 1, return false.

During the loop, we only put the condition which, when true, immediately reveals what the matrix is not (i.e., that it’s not an identity matrix)—in other words, we check for the failing of the necessary condition for a matrix to be an identity matrix. But if the diagonal entry is 1 or the non-diagonal entry is 0, we cannot decide yet on whether it is an identity matrix because diagonally 1 and non-diagonally 0 are necessary conditions for a specific iteration; for it to be a sufficient condition, we need to check all the diagonals and non-diagonals in the matrix. So, whether a matrix is an identity or not can only be decided after the entire matrix is checked. This is an essential part of learning to build algorithms, namely keeping in mind that if a necessary condition fails, we can immediately give a verdict, but if a necessary condition is met at a specific position, we still need to check further to complete the sufficient condition.


Now look at the implementation below:

Press + to interact
bool isIdentityMatrix(int M[][maxCols], int rows, int cols)
{
if (rows != cols)
return false;
else
{
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
if (r != c && M[r][c] != 0)
return false; // necessary condition of non-diagonal
// to be 0 has failed
else if(r==c && M[r][c]!=1)
return false; // necessary condition of diagonal
// to be 1 has failed
// else
// we cannot decide on any thing as both the
// necessary conditions of identity are met
// hence move to the next iterations.
}
}
return true;
}
}

Let’s create another function, printMatrixIdentity(), in which we will call the above printMatrixIdentity() function and print on the console whether the matrix is an identity matrix or not.

Press + to interact
void printMatrixIdentity(int M[][maxCols], int rows, int cols)
{
bool value = isIdentityMatrix(M, rows, cols);
if (value)
cout << "It is an Identity Matrix";
else
cout << "It is not an Identity Matrix";
}

Let’s write down the complete code below:

3 3
1 0 0
0 1 0
0 0 1




5 5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Complete program for determining if a matrix is an Identity matrix