Implement a CUDA kernel that computes the elementwise (Hadamard) product of two matrices A and B of shape (M,N), writing the result to C. For each valid index (i,j):
C[i,j]=A[i,j]⋅B[i,j]Both inputs and the output share the same shape (M,N). All three matrices are stored as row-major flat arrays of length M⋅N, so element (i,j) lives at linear index i⋅N+j.
Input: M = 2, N = 2, A = [[1, 2], [3, 4]], B = [[5, 6], [7, 8]]
Output: [[5.0, 12.0], [21.0, 32.0]]
Input: M = 2, N = 3, A = [[1, 2, 3], [4, 5, 6]], B = [[1, 0, 1], [0, 1, 0]]
Output: [[1.0, 0.0, 3.0], [0.0, 5.0, 0.0]]
Map threadIdx.y and blockIdx.y to the row i, and threadIdx.x and blockIdx.x to the column j, so each thread owns one (i,j).
Each output element depends only on the matching pair A[i,j] and B[i,j], so there is no reduction and no need for shared memory.
Because the grid is rounded up to cover any shape, some threads fall outside the matrix. An early-return bounds check on i and j keeps those threads from writing past the buffer.
Accepts: array
Accepts: array
Submit a correct solution to see your kernel performance.
Implement a CUDA kernel that computes the elementwise (Hadamard) product of two matrices A and B of shape (M,N), writing the result to C. For each valid index (i,j):
C[i,j]=A[i,j]⋅B[i,j]Both inputs and the output share the same shape (M,N). All three matrices are stored as row-major flat arrays of length M⋅N, so element (i,j) lives at linear index i⋅N+j.
Input: M = 2, N = 2, A = [[1, 2], [3, 4]], B = [[5, 6], [7, 8]]
Output: [[5.0, 12.0], [21.0, 32.0]]
Input: M = 2, N = 3, A = [[1, 2, 3], [4, 5, 6]], B = [[1, 0, 1], [0, 1, 0]]
Output: [[1.0, 0.0, 3.0], [0.0, 5.0, 0.0]]
Map threadIdx.y and blockIdx.y to the row i, and threadIdx.x and blockIdx.x to the column j, so each thread owns one (i,j).
Each output element depends only on the matching pair A[i,j] and B[i,j], so there is no reduction and no need for shared memory.
Because the grid is rounded up to cover any shape, some threads fall outside the matrix. An early-return bounds check on i and j keeps those threads from writing past the buffer.
Accepts: array
Accepts: array
Submit a correct solution to see your kernel performance.