Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a notched matrix?

I have a little problem, I don’t quite understand how to make a toothed (a notched?) matrix in C++.
The matrix should be like this (with 4 columns and 6 rows):

enter image description here

But I keep getting a matrix in the form of a triangle, i.e. no repeating rows are displayed. How can I fix it?
I’m attaching a piece of code, but I don’t think it will help much.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(N are rows, M are columns)

for (int i = 0; i < N; i++) { 
   matrix[i] = new double[M]; 
   for (int p = 0; p <= i; p++) { 
      matrix[i][p] = rand() % 101 - 50; 
   cout << setw(5) << matrix[i][p]; 
}

>Solution :

I’m assuming that the first row has 1 column, second has 2 columns, etc., up to a maximum of M columns. In which case, the below will work.

size_t N = 6;
size_t M = 4;
double **matrix = new double*[N];

for (size_t i = 0; i < N; i++) { 
   size_t cols = std::min( i + 1, M ); // determine the correct number of cols for the row
   matrix[i] = new double[cols]; 
   for (size_t p = 0; p < cols; p++) { 
      matrix[i][p] = rand() % 101 - 50; 
      cout << setw(5) << matrix[i][p]; 
   }
}

Btw, I’d suggest using something more modern than rand().

Would also generally recommend not using new, and instead preferring std::unique_ptr or std::shared_ptr, or in this case using std::vector.
Don’t forget to delete as well.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading