Mex-Code crashes during for loop at certain iteration

1 view (last 30 days)
Hello,
I wrote a mex function in order to speed up a calculation, but the code crashes whole MATLAB with a segmentation fault if I set the maximum iteration index too high.
Here is the code:
#include "mex.h"
#include "matrix.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
//declarations
float *time_series_matrix, *shapelet;
mwSize minimum_bolus_arrival, maximum_bolus_arrival, number_of_time_series, length_time_series, length_shapelet;
float *distance_matrix;
mwSize a, i, j, start_column;
float sum;
//initializations
time_series_matrix = (float *) mxGetData(prhs[0]);
shapelet = (float *) mxGetData(prhs[1]);
minimum_bolus_arrival = (mwSize) mxGetScalar(prhs[2]);
maximum_bolus_arrival = (mwSize) mxGetScalar(prhs[3]);
number_of_time_series = (mwSize) mxGetM(prhs[0]);
length_time_series = (mwSize) mxGetN(prhs[0]);
length_shapelet = (mwSize) mxGetN(prhs[1]);
plhs[0] = mxCreateNumericMatrix(number_of_time_series, (maximum_bolus_arrival - minimum_bolus_arrival), mxSINGLE_CLASS, mxREAL);
distance_matrix = (float *) mxGetData(plhs[0]);
if(maximum_bolus_arrival > (length_time_series - length_shapelet))
maximum_bolus_arrival = (length_time_series - length_shapelet);
//for every pixel (for all time series)
//time_series_matrix columnwise in memory
for (i = 0; i < 1001; i++) {
//get subsequence for each possible starting point
mexPrintf("%d\n", i);
for (j = minimum_bolus_arrival - 1; j < maximum_bolus_arrival; j++) {
start_column = j - minimum_bolus_arrival + 1;
sum = 0;
for (a = 0; a < length_shapelet; a++) {
sum = sum + (shapelet[a] - time_series_matrix[i+j*number_of_time_series+a])*(shapelet[a] - time_series_matrix[i+j*number_of_time_series+a]);
}
distance_matrix[i+start_column*number_of_time_series] = sum/length_shapelet;
}
}
}
distance_matrix is an array of 3072*500 elements. Also time_series is of larger dimensions (3072*4096). I'm sure it's not an array boundary problem. What now happens is that if I set i < 1000, everything works fine and the returned array (distance_matrix) contains the expected values. If I set i < 1001, the crash occures.
Any ideas?
Thx

Accepted Answer

Milka
Milka on 27 Sep 2013
Found the bug myself. It was a boundary problem. Just at another counter variable than expected. The 2nd for loop should be
j<maximum_bolus_arrival - 1

More Answers (0)

Categories

Find more on Programming 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!