CUDA Networks
matrix_print.cu
Go to the documentation of this file.
1 /**
2  * @file matrix_print.cu
3  * @brief Implementation of the Matrix::print method with consistent spacing.
4  */
5 #include "matrix.h"
6 #include <cuda_runtime.h>
7 #include <iostream>
8 #include <iomanip>
9 #include <cstdio>
10 
11 void Matrix::print(int decimals) {
12  // Create format string for desired number of decimals
13  char format[20];
14  sprintf(format, "%%.%df", decimals);
15 
16  // Allocate host memory to copy the data from GPU
17  double* h_data = new double[rows * cols];
18  cudaMemcpy(h_data, d_data, rows * cols * sizeof(double), cudaMemcpyDeviceToHost);
19 
20  // Print matrix dimensions
21  std::cout << "Matrix with " << rows << " rows and " << cols << " columns:\n";
22 
23  // Print column labels
24  std::cout << "\t";
25  for (int j = 0; j < cols; ++j) {
26  if (j == 4 && cols > 8) {
27  std::cout << "...\t";
28  j = cols - 4; // Skip to the last 4 columns
29  }
30  std::cout << j << ":\t";
31  }
32  std::cout << "\n";
33 
34  // Iterate over rows
35  for (int i = 0; i < rows; ++i) {
36  if (i == 5 && rows > 10) {
37  std::cout << "...\n\t";
38  for (int k = 0; k < cols; ++k) {
39  if (k == 4 && cols > 8) {
40  std::cout << "...\t";
41  k = cols - 4;
42  }
43  std::cout << "...\t";
44  }
45  std::cout << "\n";
46  i = rows - 5; // Jump to the last 5 rows
47  }
48 
49  // Print row index
50  std::cout << i << ":\t";
51 
52  // Print each element in the row
53  for (int j = 0; j < cols; ++j) {
54  if (j == 4 && cols > 8) {
55  std::cout << "...\t";
56  j = cols - 4; // Skip to the last 4 columns
57  }
58  printf(format, h_data[i * cols + j]);
59  std::cout << "\t";
60  }
61  std::cout << "\n";
62  }
63 
64  // Free the allocated host memory
65  delete[] h_data;
66  std::cout << std::endl;
67 }
void print(int decimals)
Print the matrix contents.
Definition: matrix_print.cu:11
Defines the Matrix class for GPU-accelerated matrix operations.