increase vector with mex function
1 view (last 30 days)
Show older comments
Hi *,
I would like to increase the values of a vector. I wrote two scripts:
incrementa.m
clc;
clear all;
global v
v = ones(100,1);
nvmex('incrementa.cu');
R = incrementa(v);
incrementa.cu:
int *x,*Y;
_global_ void incrementa(int *x) {
for(int i=1; i<100; i++)
x[i] = x[i]++;
}
void fz_cuda() {
printf("sono in fz_cuda()\n");
int *device_x = NULL;
// Creating objects for the measurement of the times
cudaEvent_t start,stop;
float time;
cudaEventCreate(&start);
cudaEventCreate(&stop);
// Allocation on GPU
// INPUT:
if(cudaMalloc((void**) &device_x, 100*sizeof(int)) != cudaSuccess)
mexErrMsgTxt("Memory allocating of x failure on the GPU.");
// Copy on GPU
cudaMemcpy(device_x, x, 100*sizeof(int), cudaMemcpyHostToDevice);
// ==================== // Invoke CUDA kernel // ====================
cudaEventRecord(start,0);
incrementa<<<1,1>>>(device_x);
// Copy result on CPU
cudaMemcpy(x,device_x,100*sizeof(int), cudaMemcpyDeviceToHost);
// Memory free
cudaFree(device_x);
cudaEventElapsedTime(&time, start,stop);
printf ("Tempo per il kernel: %f ms\n", time);
}
void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]) { // prhs[0] = v if (nrhs != 1)
mexErrMsgIdAndTxt("Invalid Input:nrhs","Require 1 inputs");
x = (int*)mxGetData(prhs[0]);
fz_cuda();
const mwSize outDims[2] = { 100,1 };
plhs[0] = mxCreateNumericArray(2, outDims, mxDOUBLE_CLASS, mxREAL);
Y = (int*)mxGetData( plhs[0] );
}
but this doesn't work. Where I wrong?
Thanks, Davide
0 Comments
Accepted Answer
James Tursa
on 15 Jul 2014
Edited: James Tursa
on 15 Jul 2014
I don't know about the CUDA stuff, but you have a basic mismatch of types in your C code. E.g.,
v = ones(100,1);
The above creates a double matrix at the MATLAB level.
_global_ void incrementa(int *x) {
for(int i=1; i<100; i++)
x[i] = x[i]++;
}
The above increment routine expects a pointer to int.
x = (int*)mxGetData(prhs[0]);
The above line get a pointer to the input data as an int*, even though the input data is actually double.
plhs[0] = mxCreateNumericArray(2, outDims, mxDOUBLE_CLASS, mxREAL);
Y = (int*)mxGetData( plhs[0] );
The above lines specifically create a double matrix, but you use an int* to get at the data.
So anything you do with this code will be hosed up as you are mixing int* with double data.
0 Comments
More Answers (0)
See Also
Categories
Find more on GPU Computing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!