L30 Array Dynamic1
L30 Array Dynamic1
L30 Array Dynamic1
Dynamic arrays
Dynamic Arrays
An Introduction
28 May 2024
1 0 0 0 1 0 1 0 1+1 0+0 0+1 0+0
0 1 1 0 + 0 1 0 1 = 0 + 0 1+1 1+0 0 + 1
0 0 0 1 1 0 1 0 1+1 0+0 0+1 1+0
2 0 1 0
= 0 2 1 1
2 0 1 1
Our matrices may have less than 4 rows, but must have 4 columns. This is
due to the requirement that the second array index must be a constant (4)
when sending a static array as a parameter to the functions we write.
How can we generalise this to make provision for multiple size matrices and
especially when we need to multiply matrices?
Matrix multiplication is defined as:
For matrices A of dimension m × n and B of dimension n × p:
n−1
X
Cij = Aik × Bkj , 0 ≤ i < m, 0 ≤ j < p
k=0
#i n c l u d e <i o s t r e a m >
u s i n g namespace s t d ;
i n t main ( ) {
int ∗ arr ;
int size ;
c o u t << ”The v a l u e s e n t e r e d a r e : ” ;
f o r ( i n t i = 0 ; i < s i z e ; i ++) { c o u t << a r r [ i ] << ” ” ; }
c o u t << e n d l ;
delete [ ] arr ;
return 0;
}
To help manage the matrices, write functions to allocate the memory on the
heap and free the memory from the heap representing the matrices. You can
add these functions to your matrix library.
float** allocateMatrix(int rows, int cols) {
float** matrix = new float*[rows];
for (int i = 0; i < rows; ++i)
matrix[i] = new float[cols];
return matrix;
}
return matrix;
}
What about the multiplyMatrices function? This stands over again for
homework.
Remember the definition is given by: For matrices A of dimension m × n and
B of dimension n × p:
n−1
X
Cij = Aik × Bkj , 0 ≤ i < m, 0 ≤ j < p
k=0