Table of contents
1.
Introduction
2.
Problem Statement
3.
Solution Approach
3.1.
C++ Code
3.2.
Python Code
3.3.
Java Code
4.
Frequently Asked Questions
4.1.
Can the above problem be solved with a time complexity less than O(n^2)?
4.2.
What is the space complexity of the above approach?
4.3.
What is the benefit of using a vector instead of an array in CPP?
5.
Conclusion 
Last Updated: Mar 27, 2024
Easy

Scalar Multiplication of a matrix

Author Pradeep Kumar
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will discuss how to perform scalar multiplication on a matrixScalar Multiplication is multiplying each entry of the matrix with a constant number. For the implementation, Vectors of C++ are used; if you are not familiar with vectors, you can check out this article.

Recommended Topic, Array Implementation of Queue and  Rabin Karp Algorithm

Problem Statement

Given a matrix and a scalar (let's say k), we are to compute the scalar multiplication of the matrix with k.

Examples:

Input: 3 5
           6 4
 
           k = 4

Output: 12 20
              24 16
 
Input: 9 2 3 4
           5 6 7 8
 
           k = 5
 
Output: 45 10 15 20
              25 30 35 40

Solution Approach

In this approach, we pick elements from the matrix one by one, multiply the element by scalar and store it in the matrix in the same place. The algorithm is as follows:

Step 1: Iterate over the array.

Step 2: Pick an element from the matrix

Step 3: Multiply the element by scalar and store it in the matrix at the same position.

C++ Code

// Cpp program to compute scalar Multiplication of a matrix

#include<bits/stdc++.h>
using namespace std;

// Function to print the matrix
void printMatrix(vector<vector<int>> & matrix){
    int rows = matrix.size(); // number of rows in matrix
    int cols = matrix[0].size(); // number of columns in matrix
    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j ++){
            cout<<matrix[i][j]<<" "; // print the elements of matrix
        }
        cout<<endl; // printing new line
    }
}

// Function to compute the scalar Multiplication
void scalarMultiplication(vector<vector<int>> & matrix, int k ){
    int rows = matrix.size(); // Number of rows in matrix
    int cols = matrix[0].size(); // Number of columns  in matrix

    for(int current_row = 0; current_row<rows; current_row++){
        for(int current_col = 0; current_col< cols; current_col++){
            matrix[current_row][current_col]*=k; // Multiply the element by k (scalar)
        }
    }
}

// Main function to run the program
int main(){
    // Input Matrix
    vector<vector<int>> matrix = {{ 1, 2, 3, 4 },
                      {5, 6, 7, 8},
                      {9, 10, 11 ,12},
                      {13, 14, 15, 16} };

    int k = 2; // Scalar
   
    // Print the matrix before the scalar multiplication
    cout<<"Matrix before scalar Multiplication:"<<endl;
    printMatrix(matrix); // Calling the printMatrix function to print the Matrix
   
    scalarMultiplication(matrix, k); // Calling scalarMultiplication function to compute the scalar multiplication of matrix with k

    cout<<endl; // printing new line

    // Print the matrix after the scalar multiplication
    cout<<"Matrix after scalar Multiplication with "<< k <<endl;
    printMatrix(matrix); // Calling the printMatrix function to print the Matrix


    return 0;
}

Python Code

# Python program to compute scalar Multiplication of a matrix

# Function to print the matrix
def printMatrix(matrix):
    rows = len(matrix) # number of rows in matrix
    cols = len(matrix[0]) # number of columns in matrix
    for i in range(rows):
        for j in range(cols):
            print(matrix[i][j],end = " ") # print the elements of matrix
        print() # printing new line


# Function to compute the scalar Multiplication
def scalarMultiplication(matrix, k ):
    rows = len(matrix) # number of rows in matrix
    cols = len(matrix[0]) # number of columns in matrix

    for current_row in range(rows):
        for current_col in range(cols):
            matrix[current_row][current_col]*=k # Multiply the element by k (scalar)

# Main function to run the program
if __name__ == "__main__":
    # Input Matrix
    matrix = [ [ 1, 2, 3, 4 ], [5, 6, 7, 8], [9, 10, 11 ,12], [13, 14, 15, 16] ]

    k = 2 # Scalar

    # Print the matrix before the scalar multiplication
    print("Matrix before scalar Multiplication:")
    printMatrix(matrix) # Calling the printMatrix function to print the Matrix
   
    scalarMultiplication(matrix, k) # Calling scalarMultiplication function to compute the scalar multiplication of the matrix with k

    print() # printing new line

    # Print the matrix after the scalar multiplication
    print("Matrix after scalar Multiplication with " + str(k))
    printMatrix(matrix) # Calling the printMatrix function to print the Matrix

Java Code

// Java program to compute scalar Multiplication of a matrix
class main
{
    // Function to print the matrix
static void printMatrix( int matrix[][], int rows, int cols){
    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j ++){
            System.out.print(matrix[i][j] + " ");// print the elements of matrix
        }
        System.out.println(); // printing new line
    }
}

// Function to compute the scalar Multiplication
static void scalarMultiplication(int matrix[][], int rows, int cols, int k ){
    // Iterate over the matrix
    for(int current_row = 0; current_row<rows; current_row++){
        for(int current_col = 0; current_col< cols; current_col++){
            matrix[current_row][current_col]*=k; // Multiply the element by k (scalar)
        }
    }
}

// Main function to run the program
public static void main(String[] args){
    // Input Matrix
    int rows = 4; // number of rows in matrix
    int cols = 4; // number of columns in matrix
    int matrix[][] = {{ 1, 2, 3, 4 },
                      {5, 6, 7, 8},
                      {9, 10, 11 ,12},
                      {13, 14, 15, 16} };

    int k = 2; // Scalar
   
    // Print the matrix before the scalar multiplication
    System.out.println("Matrix before scalar Multiplication:");
    printMatrix(matrix,rows,cols); // Calling the printMatrix function to print the Matrix
   
    scalarMultiplication(matrix, rows, cols, k); // Calling scalarMultiplication function to compute the scalar multiplication of matrix with k

    System.out.println(); // printing new line

    // Print the matrix after the scalar multiplication
    System.out.println("Matrix after scalar Multiplication with ");
    printMatrix(matrix,rows,cols); // Calling the printMatrix function to print the Matrix
}
}

Output:

Matrix before scalar Multiplication:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Matrix after scalar Multiplication with 2
2 4 6 8
10 12 14 16
18 20 22 24
26 28 30 32

The Time complexity of this solution is O(n^2), which is due to iterating over the matrix. 

Frequently Asked Questions

Can the above problem be solved with a time complexity less than O(n^2)?

Since to solve this problem, we need to read the element of the matrix at least once, which can not be done in less than O(n^2). Hence, the problem can not be solved with a time complexity less than O(n^2).

 

What is the space complexity of the above approach?

The space complexity of the above approach is O(1), as we are only using the unit amount of extra space. This unit space is used to store the variables like - k, iteration variables, etc.

 

What is the benefit of using a vector instead of an array in CPP?

A vector is a dynamic array. Its size can be extended, but the array's size cannot be modified. Vectors can have reserved space, while arrays cannot.

Conclusion 

In this article, we have extensively discussed the approach to computing the scalar multiplication of a matrix. We hope that this blog has helped you enhance your knowledge, to learn more, check out our article on Find the first, second, and third minimum elements in an array

And also, check out the awesome content on the Coding Ninjas Website,
Android DevelopmentCoding Ninjas Studio ProblemsCoding Ninjas Studio Interview BundleCoding Ninjas Studio Interview ExperiencesCoding Ninjas CoursesCoding Ninjas Studio Contests, and Coding Ninjas Studio Test SeriesDo upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass