In: Computer Science
In this assignment, you implement a 2D-matrix as a vector of vectors, and only use at() to access its elements.
Write a program that multiplies a 2D matrix with a vector. If you need to see the math, follow this link: https://mathinsight.org/matrix_vector_multiplication (Links to an external site.)
For simplicity, our matrix will be of size 3 x 3. Initialize the matrix as shown in to become
[1.0, 2.0, 3.0]
[4.0 ,5.0 ,6.0]
[7.0, 8.0, 9.0]
Read the three values of the vector to be multiplied on the right of the matrix from the user input. Then, multiply it and print the resulting vector to cout. The interaction should look like this:
Please enter the three vector coefficients 1 1 1 The result vector is [6, 15, 24]
Write a function that takes the matrix and the right-side vector as parameters and that returns the vector resulting from the multiplication.
The program must not use arrays, only vectors.
this program should be programmed using c++ only
C++ code:
//=========================================================
#include <iostream>
#include <vector>
using namespace std;
// user can update if he want to multiple other sized matrix to
vector
// where matrix size is SIZE_MxSIZE_N and vector size is
SIZE_Nx1
// result vector size is SIZE_Mx1
#define SIZE_M 3
#define SIZE_N 3
vector<float>
multiply_matrix_vector(vector<vector<float>> mat,
vector<float> vect)
{
// creating a output vector that will store
multiplication output
vector<float> result(SIZE_M);
for (int i = 0; i < SIZE_M; i++)
{
//initializing ith position of
vector
result.at(i) = 0;
for (int j = 0; j < SIZE_N;
j++)
{
//calculating
sum of ai1*x1 + ai2*x2 ... +aij*xj + .... + ain*xn
result.at(i) =
result.at(i) + mat.at(i).at(j)*vect.at(j);
}
}
// return result vector
return result;
}
int main()
{
// creating vector of vector with data type
double
// because in question numbers are decimal number
(float)
vector<vector<float>> mat{ { 1.0, 2.0, 3.0
},
{ 4.0, 5.0, 6.0 },
{ 7.0, 8.0, 9.0 } };
// creating a right vector with size 3;
vector<float> vect(SIZE_N);
cout << "Please enter the three vector
coefficients" <<endl;
// read input vector coefficients
for (int i = 0; i < SIZE_N; i++)
cin >> vect.at(i);
// multiply_matrix_vector function is called for
mutilplication of matrix and right vector
// result is stored in result vector
vector<float> result =
multiply_matrix_vector(mat, vect);
//print result vector
cout << "The result vector is [";
for (int i = 0; i < SIZE_M-1; i++)
cout<< result.at(i)<<",
";
cout << result.at(SIZE_M - 1) << ']'
<< endl;
return 0;
}
//=========================================================
output 1:
output 2: