CUDA Networks
Functions
matrix_randomize.cu File Reference

Implementation of the Matrix::randomize method to fill the matrix with random values. More...

#include "matrix.h"
#include <curand_kernel.h>
#include <cuda_runtime.h>
Include dependency graph for matrix_randomize.cu:

Go to the source code of this file.

Functions

__global__ void randomizeKernel (double *data, int rows, int cols, unsigned long seed)
 CUDA kernel function that fills each element in the matrix with a random value between -0.5 and 0.5. More...
 

Detailed Description

Implementation of the Matrix::randomize method to fill the matrix with random values.

Definition in file matrix_randomize.cu.

Function Documentation

◆ randomizeKernel()

__global__ void randomizeKernel ( double *  data,
int  rows,
int  cols,
unsigned long  seed 
)

CUDA kernel function that fills each element in the matrix with a random value between -0.5 and 0.5.

Parameters
dataPointer to the matrix data on the GPU.
rowsNumber of rows in the matrix.
colsNumber of columns in the matrix.
seedSeed for random number generator.

Definition at line 17 of file matrix_randomize.cu.

17  {
18  // Calculate the global thread index
19  int idx = blockIdx.x * blockDim.x + threadIdx.x;
20  int totalElements = rows * cols;
21 
22  // Ensure the thread's index is within the matrix bounds
23  if (idx < totalElements) {
24  // Calculate the row and column for this thread
25  int row = idx / cols;
26  int col = idx % cols;
27 
28  // Initialize a random state for this thread
29  curandState state;
30  curand_init(seed, idx, 0, &state);
31 
32  // Generate a random value between 0 and 1, then shift it to be between -0.5 and 0.5
33  double randomValue = curand_uniform(&state) - 0.5;
34 
35  // Assign the random value to the current matrix element
36  data[row * cols + col] = randomValue;
37  }
38 }