# Matrix Addition

**URL:** <https://forums.developer.nvidia.com/t/matrix-addition/26909>\
**Category:** CUDA Programming and Performance\
**Created:** [June 14, 2012, 2:42am UTC](https://forums.developer.nvidia.com/t/matrix-addition/26909 "2012-06-14T02:42:59Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![wolfshark](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@wolfshark](https://forums.developer.nvidia.com/u/wolfshark)\
**Post date:** [June 14, 2012, 2:42am UTC](https://forums.developer.nvidia.com/t/matrix-addition/26909/1 "2012-06-14T02:42:59Z")

</div>

Apologies. (I posted in wrong section before)

Hi, I am very fresh in learning CUDA and I need some help adding matrices. So far i have this as my adding function:

#define N 3  
const dim3 threadsPerBlock(N, N);  
const dim3 numBlocks(N / threadsPerBlock.x, N / threadsPerBlock.y);

**global** void compute(int a[N][N], int b[N][N], int c[N][N])  
{  
int i = blockIdx.x \* blockDim.x + threadIdx.x;  
int j = blockIdx.y \* blockDim.y + threadIdx.y;  
if (i \< N && j \< N)  
c[i][j] = a[i][j] + b[i][j];  
}

It is very similar to the NVIDIA programming guide example.  
From there i have:

int main(void)  
{  
int a[N][N], b[N][N], c[N][N];  
int dev\_a[N][N], dev\_b[N][N], dev\_c[N][N];

cudaMalloc( (void\*\*)&dev\_a, (N_N)sizeof(int) );  
cudaMalloc( (void\*)&dev\_b, (N_N)_sizeof(int) );  
cudaMalloc( (void_\*)&dev\_c, (N\*N)\*sizeof(int) );

//THEN I FILL THE MATRICES UP WITH RANDOM NUMBERS

and finish off with this:

cudaMemcpy(dev\_a, a, (N\*N)_sizeof(int), cudaMemcpyHostToDevice);  
cudaMemcpy(dev\_b, b, (N_N)\*sizeof(int), cudaMemcpyHostToDevice);

compute\<\<\<numBlocks,threadsPerBlock\>\>\>(dev\_a, dev\_b,dev\_c);

cudaMemcpy(c,dev\_c, (N\*N)\*sizeof(int), cudaMemcpyDeviceToHost);

The addition is not happening. Can anyone see where i went wrong? Thanks.

---

<div class="post-metadata">

**Author:** ![Gilles\_C](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@Gilles\_C](https://forums.developer.nvidia.com/u/Gilles_C)\
**Post date:** [June 14, 2012, 7:35am UTC](https://forums.developer.nvidia.com/t/matrix-addition/26909/2 "2012-06-14T07:35:49Z")

</div>

Hi,  
Your kernel’s parameters are not to be define as 2D arrays, but rather as 1D pointers. To access the data at index (i,j), use “a[j\*N+i]”.  
In addition, I’m not too sure if your host’s 2D automatic arrays can be used directly for cudaMemcpy. I wouldn’t do like this, but my knowledge of the C standard dark corners is not sufficient to say if this is actually wrong, or just super counter-intuitive.
