Write a function mat_mult() that has accepts two 3x3 matrices matA and matB as i
ID: 3641365 • Letter: W
Question
Write a function mat_mult() that has accepts two 3x3 matrices matA and matB as input and returns a pointer to an output matrix that is the product of the two input matrices. Pointers to MatA and MatB are passed from main() to mat_mult(). The output matrix is dynamically allocated on the heap. main() prints the contents of the output matrix. The prototype for mat_mult() isint **mat_mult(int *matA, int *matB, int row, int col)
// Demonstrates how to allocate two dimensional dynamic arrays in C++
#include <iostream>
using namespace std;
int main()
{
int i, j;
int row = 3, col = 3;
// Allocate array in heap
// Allocate a row of pointers and store a pointer to this row of pointers in m
int **m = new int* [row];
// Allocate a column of integers and store a pointer to col i in m[i]
for (i = 0; i < row; i++)
m[i] = new int [col];
// Input array. Each array element is assigned the sum of its row and col values
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
m[i][j] = i + j;
// Output array
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++)
cout << m[i][j] << " ";
cout << endl;
}
// Delete array
for (i = 0; i < row; i++)
delete [] m[i];
delete [] m;
return 0;
}
// Mat_Add is a function that returns a pointer to a matrix obtained by summing two input matrices
#include <iostream>
using namespace std;
int **Mat_Add(int *matA, int *matB, int row, int col);
int main()
{
int i, j;
int row = 3, col = 3;
int matA[row][col], matB[row][col];
int **matC;
// Input Arrray
for (i = 0; i < row; i++)
for(j = 0; j < col; j++) {
matA[i][j] = i + j;
matB[i][j] = i + j;
}
// Call the matrix addition function
matC = Mat_Add(&matA[0][0], &matB[0][0], row, col);
// Output array
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++)
cout << matC[i][j] << " ";
cout << endl;
}
// Delete array
for (i = 0; i < row; i++)
delete [] matC[i];
delete [] matC;
return 0;
}
int **Mat_Add(int *matA, int *matB, int row, int col)
{
int i, j;
// Allocate array in heap
// Allocate a row of pointers and store a pointer to this row of pointers in m
int **temp = new int* [row];
// Allocate a column of integers and store a pointer to col i in m[i]
for (i = 0; i < row; i++)
temp[i] = new int [col];
// Input array. Each array element is assigned the sum of its row and col values
for (i = 0; i < row; i++)
for (j = 0; j < col; j++)
temp[i][j] = *(matA + i + j) + *(matB + i + j);
return temp;
}
Explanation / Answer
int main() { int i, j; int row = 3, col = 3; int matA[row][col], matB[row][col]; int **matC; // Input Arrray for (i = 0; iRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.