'How can I encapsulate code dealing with matrices and make it reusable?

At my course we are getting tasks that always start with filling a random matrix size nxm with random numbers.

I want to create(a library?, a class?) some structure so than any time I want to generate a matrix A I would need just to input the desired size nxm.

In other words, change all this code for something like #include <myrandommatrixgenerator>.

int n, m;

cout << "Enter number of rows (n): ";
cin >> n;
cout << "Enter number of columns (m): ";
cin >> m;

//matrix b with random numbers
srand(time(NULL));

int max = 9, min = -9;

int *b = new int[n*m];
for (int i = 0; i<n; i++)
{
    for (int j = 0; j<m; j++)
    {
        b[i*m + j] = min + ((rand() % max) + 1);
    }
}

//print matrix b
cout << "\nMatrix b:" << endl;

for (int i = 0; i<n; i++)
{
    for (int j = 0; j<m; j++)
    {
        cout << setw(5) << b[i*m + j];
    }
    cout << endl;
}

I do not have a broad overview of the possibilities with C++, so what is the structure that allow me to do that?



Solution 1:[1]

Below is an outline of what you can do to achieve that:

  1. Define a class e.g. MyMatrix. A class can encapsulate data and operations related to it. The class can be placed in separate files (h and cpp). A friendly guide: C++ Classes and Objects - w3schooles.
  2. This class should use e.g. a std::vector to hold the data (better than using raw pointers like in your code).
  3. This class should have public methods for getting the metadata (n,m) and data.
  4. This class should have a public method, e.g.: InitRandom(int n, int m), to initialize the MyMatrix object to a matrix size n x m with random values.
  5. In another part of your program you can #include your class h file, and then instantiate a MyMatrix object, and use InitRandom to do what you need.

You can see here a discussion about implementing a matrix class: https://codereview.stackexchange.com/questions/155811/basic-matrix-class-in-c

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1