Skip to content

W5 ‐ Matrices operation (ASSESSED)

Riccardo Polvara edited this page Oct 30, 2025 · 3 revisions

CMP9133 - Workshop 5

University of Lincoln

School of Computer Science

CMP9133 – Programming Principles

Landing page

Join the fifth workshop (the second assessed) at the dedicated LINK 💻

Task (assessed)

You are tasked with writing a C++ program that performs basic matrix operations, including addition and multiplication. Your program should demonstrate your understanding of dynamic memory allocation, pointer arithmetic, and matrix manipulation.

Instructions:

  1. Define a class named Matrix with the following private attributes:
    • An integer pointer named data to store the matrix data as a 2D array.
    • Integer variables rows and cols to store the dimensions of the matrix.
  2. Implement the following methods for the Matrix class:
    • A constructor that takes integer parameters r and c to initialize the matrix dimensions. It should allocate memory for the matrix data.
    • A destructor that deallocates memory for the matrix data.
    • int get(int row, int col): Returns the value at the given row and column indices.
    • void set(int row, int col, int value): Sets the value at the given row and column indices.
  3. Implement the following operations as member methods of the Matrix class:
    • Matrix add(const Matrix &other): Returns a new matrix that is the sum of the current matrix and the other matrix.
    • Matrix multiply(const Matrix &other): Returns a new matrix that is the product of the current matrix and the other matrix.

Test case:

2b3ddaf9-a834-449a-b297-f2dc5d3808a0

Make sure to handle memory allocation, deallocation, and matrix operations correctly in your program. This assessment will help assess your understanding of memory management, pointers, and matrix operations in C++.

Note: Suppose $A = [a_{ij}]_{mxn}$ and $B = [b_{ij}]_{mxn}$ are two matrices of order $m x n$, then the addition of $A$ and $B$ is given by:

$$ A + B = [a_{ij}]_{mxn} + [b_{ij}]_{mxn} = [a_{ij} + b_{ij}]_{mxn} $$

Note2: The addition between two matrices is allowed only if they have the same size. Note3: Consider matrix $A$ which is $a × b$ matrix and matrix $B$, which is a $b × c$ matrix. Then, matrix $C = AB$ is defined as the $A × B$ matrix. An element in matrix $C$, $C_{xy}$ is defined as:

$$ C_{xy} = A_{x1}B_{y1} + ... + A_{xb}B_{yb} = \displaystyle\sum_{k=1}^b A_{xk}B_{ky} $$

For $x = 1…… a$  and $y= 1……c$ .

Clone this wiki locally