Home > Software engineering >  How to make a notched matrix?
How to make a notched matrix?

Time:12-17

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.

(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]; 
}

CodePudding user response:

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.

  • Related