Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Matlab Crashes at the end of a Mex Function

Subject: Matlab Crashes at the end of a Mex Function

From: Hariprasad

Date: 4 Sep, 2013 09:37:09

Message: 1 of 8

I'm writing a Mex Function to calculate Kmeans clustering. I tried running each part of the code as a separate Mex function with dummy inputs, they all worked fine and finally after debugging the whole code, when I run the main Mex Function, it runs till the end of the code but just before exiting the function, MATLAB crashes giving a
Segmentation violation error.
Please let me know where i can paste my code.

Subject: Matlab Crashes at the end of a Mex Function

From: Steven_Lord

Date: 4 Sep, 2013 14:29:47

Message: 2 of 8



"Hariprasad " <sudharshan_hari@yahoo.co.in> wrote in message
news:l06v05$bl7$1@newscl01ah.mathworks.com...
> I'm writing a Mex Function to calculate Kmeans clustering. I tried running
> each part of the code as a separate Mex function with dummy inputs, they
> all worked fine and finally after debugging the whole code, when I run the
> main Mex Function, it runs till the end of the code but just before
> exiting the function, MATLAB crashes giving a
> Segmentation violation error.
> Please let me know where i can paste my code.

If the code is long, why don't you start the debugging process by following
the instructions for debugging MEX-files to try to localize the problem to a
small section of the code?

http://www.mathworks.com/help/matlab/matlab_external/debugging-c-c-language-mex-files.html

Once you've narrowed down the source of the problem to a small section of
code (say one particular function) then posting that small section to the
newsgroup would allow readers to help debug the problem the rest of the way
more quickly.

--
Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on
http://www.mathworks.com

Subject: Matlab Crashes at the end of a Mex Function

From: TideMan

Date: 4 Sep, 2013 21:05:41

Message: 3 of 8

On Wednesday, September 4, 2013 9:37:09 PM UTC+12, Hariprasad wrote:
> I'm writing a Mex Function to calculate Kmeans clustering. I tried running each part of the code as a separate Mex function with dummy inputs, they all worked fine and finally after debugging the whole code, when I run the main Mex Function, it runs till the end of the code but just before exiting the function, MATLAB crashes giving a
>
> Segmentation violation error.
>
> Please let me know where i can paste my code.

In my experience (Fortran, not C), this always indicates that an array has not been deallocated before exiting the Mex function. In Fortran the command is:
deallocate(array1,array2)
There is probably an equivalent in C.

Subject: Matlab Crashes at the end of a Mex Function

From: James Tursa

Date: 5 Sep, 2013 00:48:06

Message: 4 of 8

TideMan <mulgor@gmail.com> wrote in message <41f64e36-0b4c-48c9-9b40-cd807b54b943@googlegroups.com>...
> On Wednesday, September 4, 2013 9:37:09 PM UTC+12, Hariprasad wrote:
> > I'm writing a Mex Function to calculate Kmeans clustering. I tried running each part of the code as a separate Mex function with dummy inputs, they all worked fine and finally after debugging the whole code, when I run the main Mex Function, it runs till the end of the code but just before exiting the function, MATLAB crashes giving a
> >
> > Segmentation violation error.
> >
> > Please let me know where i can paste my code.
>
> In my experience (Fortran, not C), this always indicates that an array has not been deallocated before exiting the Mex function. In Fortran the command is:
> deallocate(array1,array2)
> There is probably an equivalent in C.

I unaware of any deallocation issues causing mex crashes. I can understand a memory leak, but why would failing to deallocate memory cause a crash? Can you give an example?

James Tursa

Subject: Matlab Crashes at the end of a Mex Function

From: Hariprasad

Date: 5 Sep, 2013 04:35:05

Message: 5 of 8

"Steven_Lord" <slord@mathworks.com> wrote in message <l07g4r$duh$1@newscl01ah.mathworks.com>...
>
>
> "Hariprasad " <sudharshan_hari@yahoo.co.in> wrote in message
> news:l06v05$bl7$1@newscl01ah.mathworks.com...
> > I'm writing a Mex Function to calculate Kmeans clustering. I tried running
> > each part of the code as a separate Mex function with dummy inputs, they
> > all worked fine and finally after debugging the whole code, when I run the
> > main Mex Function, it runs till the end of the code but just before
> > exiting the function, MATLAB crashes giving a
> > Segmentation violation error.
> > Please let me know where i can paste my code.
>
> If the code is long, why don't you start the debugging process by following
> the instructions for debugging MEX-files to try to localize the problem to a
> small section of the code?
>
> http://www.mathworks.com/help/matlab/matlab_external/debugging-c-c-language-mex-files.html
>
> Once you've narrowed down the source of the problem to a small section of
> code (say one particular function) then posting that small section to the
> newsgroup would allow readers to help debug the problem the rest of the way
> more quickly.
>
> --
> Steve Lord
> slord@mathworks.com
> To contact Technical Support use the Contact Us link on
> http://www.mathworks.com

I tried debugging till the end of the code, as i mentioned. Just when the function is supposed to come out, MATLAB stops responding sometimes times with a message saying MATLAB has stopped responding or gives the Segmentation Violation error. I also got a couple of errors while debugging in Visual Studio 2008 as these: -

Unhandled exception at 0x77b42d24 in MATLAB.exe: 0xC0000005: Access violation writing location 0x14b61f1e.

Unhandled exception at 0x77bb380b in MATLAB.exe: 0xC0000374: A heap has been corrupted.

Subject: Matlab Crashes at the end of a Mex Function

From: Hariprasad

Date: 5 Sep, 2013 05:51:12

Message: 6 of 8

"Hariprasad" wrote in message <l091lp$hlb$1@newscl01ah.mathworks.com>...
> "Steven_Lord" <slord@mathworks.com> wrote in message <l07g4r$duh$1@newscl01ah.mathworks.com>...
> >
> >
> > "Hariprasad " <sudharshan_hari@yahoo.co.in> wrote in message
> > news:l06v05$bl7$1@newscl01ah.mathworks.com...
> > > I'm writing a Mex Function to calculate Kmeans clustering. I tried running
> > > each part of the code as a separate Mex function with dummy inputs, they
> > > all worked fine and finally after debugging the whole code, when I run the
> > > main Mex Function, it runs till the end of the code but just before
> > > exiting the function, MATLAB crashes giving a
> > > Segmentation violation error.
> > > Please let me know where i can paste my code.
> >
> > If the code is long, why don't you start the debugging process by following
> > the instructions for debugging MEX-files to try to localize the problem to a
> > small section of the code?
> >
> > http://www.mathworks.com/help/matlab/matlab_external/debugging-c-c-language-mex-files.html
> >
> > Once you've narrowed down the source of the problem to a small section of
> > code (say one particular function) then posting that small section to the
> > newsgroup would allow readers to help debug the problem the rest of the way
> > more quickly.
> >
> > --
> > Steve Lord
> > slord@mathworks.com
> > To contact Technical Support use the Contact Us link on
> > http://www.mathworks.com
>
> I tried debugging till the end of the code, as i mentioned. Just when the function is supposed to come out, MATLAB stops responding sometimes times with a message saying MATLAB has stopped responding or gives the Segmentation Violation error. I also got a couple of errors while debugging in Visual Studio 2008 as these: -
>
> Unhandled exception at 0x77b42d24 in MATLAB.exe: 0xC0000005: Access violation writing location 0x14b61f1e.
>
> Unhandled exception at 0x77bb380b in MATLAB.exe: 0xC0000374: A heap has been corrupted.
I also deallocate\destroy the variables created using mxArray using mxDestroyArray. All these arrays are used inside the function only, not returned as output.
Hari

Subject: Matlab Crashes at the end of a Mex Function

From: Hariprasad

Date: 5 Sep, 2013 06:22:05

Message: 7 of 8

"Hariprasad" wrote in message <l0964g$bqu$1@newscl01ah.mathworks.com>...
> "Hariprasad" wrote in message <l091lp$hlb$1@newscl01ah.mathworks.com>...
> > "Steven_Lord" <slord@mathworks.com> wrote in message <l07g4r$duh$1@newscl01ah.mathworks.com>...
> > >
> > >
> > > "Hariprasad " <sudharshan_hari@yahoo.co.in> wrote in message
> > > news:l06v05$bl7$1@newscl01ah.mathworks.com...
> > > > I'm writing a Mex Function to calculate Kmeans clustering. I tried running
> > > > each part of the code as a separate Mex function with dummy inputs, they
> > > > all worked fine and finally after debugging the whole code, when I run the
> > > > main Mex Function, it runs till the end of the code but just before
> > > > exiting the function, MATLAB crashes giving a
> > > > Segmentation violation error.
> > > > Please let me know where i can paste my code.
> > >
> > > If the code is long, why don't you start the debugging process by following
> > > the instructions for debugging MEX-files to try to localize the problem to a
> > > small section of the code?
> > >
> > > http://www.mathworks.com/help/matlab/matlab_external/debugging-c-c-language-mex-files.html
> > >
> > > Once you've narrowed down the source of the problem to a small section of
> > > code (say one particular function) then posting that small section to the
> > > newsgroup would allow readers to help debug the problem the rest of the way
> > > more quickly.
> > >
> > > --
> > > Steve Lord
> > > slord@mathworks.com
> > > To contact Technical Support use the Contact Us link on
> > > http://www.mathworks.com
> >
> > I tried debugging till the end of the code, as i mentioned. Just when the function is supposed to come out, MATLAB stops responding sometimes times with a message saying MATLAB has stopped responding or gives the Segmentation Violation error. I also got a couple of errors while debugging in Visual Studio 2008 as these: -
> >
> > Unhandled exception at 0x77b42d24 in MATLAB.exe: 0xC0000005: Access violation writing location 0x14b61f1e.
> >
> > Unhandled exception at 0x77bb380b in MATLAB.exe: 0xC0000374: A heap has been corrupted.
> I also deallocate\destroy the variables created using mxArray using mxDestroyArray. All these arrays are used inside the function only, not returned as output.

One more doubt. in my code, for some double *arrays, i overwrite data into them since there are a lot of iterations in the function. But the size of the arrays and the the data type are constant through out during each overwrite. Will this cause any Problem??
Hari

Subject: Matlab Crashes at the end of a Mex Function

From: Hariprasad

Date: 5 Sep, 2013 10:22:14

Message: 8 of 8

"Hariprasad" wrote in message <l097ud$5q1$1@newscl01ah.mathworks.com>...
> "Hariprasad" wrote in message <l0964g$bqu$1@newscl01ah.mathworks.com>...
> > "Hariprasad" wrote in message <l091lp$hlb$1@newscl01ah.mathworks.com>...
> > > "Steven_Lord" <slord@mathworks.com> wrote in message <l07g4r$duh$1@newscl01ah.mathworks.com>...
> > > >
> > > >
> > > > "Hariprasad " <sudharshan_hari@yahoo.co.in> wrote in message
> > > > news:l06v05$bl7$1@newscl01ah.mathworks.com...
> > > > > I'm writing a Mex Function to calculate Kmeans clustering. I tried running
> > > > > each part of the code as a separate Mex function with dummy inputs, they
> > > > > all worked fine and finally after debugging the whole code, when I run the
> > > > > main Mex Function, it runs till the end of the code but just before
> > > > > exiting the function, MATLAB crashes giving a
> > > > > Segmentation violation error.
> > > > > Please let me know where i can paste my code.
> > > >
> > > > If the code is long, why don't you start the debugging process by following
> > > > the instructions for debugging MEX-files to try to localize the problem to a
> > > > small section of the code?
> > > >
> > > > http://www.mathworks.com/help/matlab/matlab_external/debugging-c-c-language-mex-files.html
> > > >
> > > > Once you've narrowed down the source of the problem to a small section of
> > > > code (say one particular function) then posting that small section to the
> > > > newsgroup would allow readers to help debug the problem the rest of the way
> > > > more quickly.
> > > >
> > > > --
> > > > Steve Lord
> > > > slord@mathworks.com
> > > > To contact Technical Support use the Contact Us link on
> > > > http://www.mathworks.com
> > >
> > > I tried debugging till the end of the code, as i mentioned. Just when the function is supposed to come out, MATLAB stops responding sometimes times with a message saying MATLAB has stopped responding or gives the Segmentation Violation error. I also got a couple of errors while debugging in Visual Studio 2008 as these: -
> > >
> > > Unhandled exception at 0x77b42d24 in MATLAB.exe: 0xC0000005: Access violation writing location 0x14b61f1e.
> > >
> > > Unhandled exception at 0x77bb380b in MATLAB.exe: 0xC0000374: A heap has been corrupted.
> > I also deallocate\destroy the variables created using mxArray using mxDestroyArray. All these arrays are used inside the function only, not returned as output.
>
> One more doubt. in my code, for some double *arrays, i overwrite data into them since there are a lot of iterations in the function. But the size of the arrays and the the data type are constant through out during each overwrite. Will this cause any Problem??
Just to get an idea, here is my full code: -

/* Kmeans Clustering for Customer Segmentation
Mex_Kmeans */

#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "mat.h"
#include <mex.h> /* Definitions for Matlab API */
#include <matrix.h>


/* Input Arguments
#define input_train prhs[0]
#define no_of_levels prhs[1]
#define First_Run prhs[2]

   Output Arguments
#define Xk plhs[0]
#define assignment plhs[1]
#define ave_dist plhs[2]
#define all_ave_dist[3] */


/*#define rows(x) (sizeof(x)/sizeof(x[0]))
#define cols(x) (sizeof(x)/sizeof(x[0]))/rows(x) */


void distance (double input_train[], int m, int n, double out_levels[], int y, double *dist)
{
 double tmp1 = 0;
 double tmp2 = 0;
 int i,j,k;
 for (j = 0; j < y; j++)
 {
  for (i = 0; i < n; i++)
{
for (k =0; k < 2; k++)
{
/*mexPrintf("input[%d][%d] = %f\n outlevel[%d][%d] = %f\n",k,i,input_train[i*2+k],k,j,out_levels[j*2+k]); */
tmp1 = input_train[(i*2) + (k)] - out_levels[(j*2) + (k)]; /* input_train[2][n] size and out_levels[2][4] size */
tmp1 = tmp1 * tmp1;
tmp2 = tmp2 + tmp1;
tmp1 = 0;
if(k == 1)
{
dist[(i) + (n*j)] = tmp2; /*tmp1 + tmp2;*/
tmp2 = 0;
}
}
/*tmp2 = input_train[i*y + j] - out_levels[i*y + j];
tmp1 = tmp1 * tmp1;
tmp2 = tmp2 * tmp2; */
}
 }

}

void random_generator(int rows,int cols,double* randnums)
{ /* Random Number Generation */

    int i,j;
    srand (time(NULL));
    for (i = 0; i < rows; i++)
    {
        for(j = 0; j < cols; j++)
        {
            randnums[(i*cols) + (j)] = (double)rand() / RAND_MAX ;
        }
    }

}

double fnmax(double input_train[], int m, int n, int dim, int rc) /* for finding Max of the array */
{
double output;
    int i,j;
    /* rc is a particular row or column */
if(dim == 1) /* max(data,[],1) Column chk */
{
        if(rc == 1)
        {rc--;}
if(rc > 2)
        {rc = rc + rc-2;}

output = input_train[rc];
/*mexPrintf("input[%d] = %f\n",rc,input_train[rc]);*/
for(i = rc+1; i <= rc+1; i++)
{
/*mexPrintf("input[%d] = %f\n",i,input_train[i]);*/
if(input_train[i] > output)
{
output = input_train[i];
}
}
}
else if(dim == 2) /* max(data,[],2) Row chk */
{
        if(rc > m)
        { /* mexPrintf(" Array dimension(Rows=%d) less than the specified dimesion(rc = %d)\n",m,rc);*/
            mexErrMsgTxt("Array dimension(Rows) less than the specified dimesion(rc)\nCheck the dimentions specified\n");
            return 0;
        }
if(rc == 1 || rc == 2)
        {rc = rc - 1;}
               
output = input_train[rc-1];
/*mexPrintf("input[%d] = %f\n",rc,input_train[rc]);*/
for (j = rc; j < n*m; j+=2)
{
/*mexPrintf("input[%d] = %f\n",j,input_train[j]);*/
if(input_train[j] > output)
{
output = input_train[j];
}
}
}
return(output);
}

double fnmin(double input_train[], int m, int n ,int dim, int rc) /* for finding Min of the array */
{
double output;
    int i,j;
if(dim == 1) /* min(data,[],1) Column chk */
{
        if(rc == 1)
        {rc--;}
if(rc > 2)
        {rc = rc + rc-2;}

output = input_train[rc];
/* mexPrintf("input[%d] = %f\n",rc,input_train[rc]); */
for(i = rc+1; i <= rc+1; i++)
{
/* mexPrintf("input[%d] = %f\n",i,input_train[i]); */
if(input_train[i] < output)
{
output = input_train[i];
}
}
}
else if(dim == 2) /* min(data,[],2) Row chk */
{
        if(rc > m)
        { /* mexPrintf(" Array dimension(Rows=%d) less than the specified dimesion(rc = %d)\n",m,rc);*/
            mexErrMsgTxt("Array dimension(Rows) less than the specified dimesion(rc)\nCheck the dimentions specified\n");
            return 0;
        }
if(rc == 1 || rc == 2)
        {rc = rc - 1;}
               
output = input_train[rc-1];
/* mexPrintf("input[%d] = %f\n",rc,input_train[rc]); */
for (j = rc; j < n*m; j+=2)
{
/* mexPrintf("input[%d] = %f\n",j,input_train[j]); */
if(input_train[j] < output)
{
output = input_train[j];
}
}
}
return(output);
}

void rep_mat(double data,int rows,int cols,double *output)
{
    int i,j;
    for(i = 0; i < rows; i++)
    {
        for(j = 0; j < cols; j++)
        {
            output[(i*cols) + (j)] = data;
        }
    }
}
/* The Main Kmeans Function definition Starts here
 void Mex_Kmeans ( double *input_train[], -- Input Data
                        int dim, -- Size of input_train
                   int no_of_levels, -- no.of Segments
                   int First_Run, -- First_run = 1 or 0 for Learning Mode
                   double *Xk[], -- Outputs
                   double *ave_dist, -- Outputs
                   double *all_ave_dist[], -- Outputs
                   int *assignment[] -- Outputs
                  ) */
void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    /* ---- Inputs ----
* prhs[0] = input_train
     * prhs[1] = no_of_levels;
     * prhs[2] = First_Run;
     
---- Outputs ----
     * plhs[0] = Xk;
     * plhs[1] = ave_dist;
     * plhs[2] = all_ave_dist;
     * plhs[3] = assignment;
     */
    
/* Initialize Required parameters */
    int no_of_levels,First_Run;
    double *input_train;
    
    /* variables for intra-function calculation */
    double *out_levels, *final_ave_dist, *final_out_levels, *final_assignment;
    /*int *final_assignment; */
    
    double *randoms1, *randoms2, *dist, *min_dist, *min_ind, *mapping; /* *tmpreps, */
    
    /* Outputs Parameters*/
    double *Xk, *ave_dist, *all_ave_dist,*assignment;
   
    /* int *assignment; */
    int m, n ; /* size of input_train MxN = 2xn */
    int x, y; /* size of Out_levels XxY = 2x4 */
    /* pointer to hold major intra-function variables */
    mxArray *in_Xk_Base;
   /* mxArray *in_var1, *in_var2, *in_var3, *in_var4,*in_Xk_Base;
    mxArray *dist_ptr, *rand_ptr1, *rand_ptr2, *min_dist_ptr, *min_ind_ptr, *mapp_ptr; */
    
    int i,j,k,w,iter,no_iter,ii;
    double *Xk_Base;

MATFile *pmat;
    const char *file = "Kmeans_Base.mat";
    
double ave_dist_old,ave_dist_new;
    double tmp,max_val[2],min_val[2];
    
    int cnt = 0;
    /* double min_dist[2];
       int min_ind[2]; */
    
    double avg,sum = 0;
    double min_over_all_iter;
    int min_ind_over_all_iter;
    mwSize ndim = 3;
mwSize dims[3];
    
    /* Error checks */
    if (nrhs != 3) {
        mexErrMsgTxt("3 input arguments required.");
    } else if (nlhs != 4) {
        mexErrMsgTxt("4 output arguments required.");
    }
           
    /* Input Arguments being extracted ----------------------------------*/
    input_train = mxGetData(prhs[0]);
    no_of_levels = (int) mxGetScalar(prhs[1]);
    First_Run = (int) mxGetScalar(prhs[2]);
    if(First_Run == 1) {
        no_iter = 100;
    } else if(First_Run == 0) {
        no_iter = 1;
    }
    m = (int) mxGetM(prhs[0]);
    n = (int) mxGetN(prhs[0]);
    x = m; y = no_of_levels;
    
    dims[0] = m; dims[1] = no_of_levels; dims[2] = no_iter;
    
    /*--------------------------------------------------------------------
    --------------- Output Arguments being initialized ----------------- */
    plhs[0] = mxCreateDoubleMatrix(m,no_of_levels,mxREAL);
    Xk = mxGetPr(plhs[0]); /* Xk = m x no_of_levels*/
    
plhs[1] = mxCreateDoubleMatrix(n,1,mxREAL);
    assignment = mxGetPr(plhs[1]); /* assignment = n x 1 */

    plhs[2] = mxCreateDoubleMatrix(1,1,mxREAL);
    ave_dist = mxGetPr(plhs[2]); /* ave_dist = 1x1 */
    
    plhs[3] = mxCreateDoubleMatrix(no_iter,1,mxREAL);
    all_ave_dist = mxGetPr(plhs[3]); /* all_ave_dist = no_iter x 1 */

    /* -------------------------------------------------------------------*/
    
    
  /* in_var1 = mxCreateDoubleMatrix(m,no_of_levels,mxREAL);
    out_levels = mxGetPr(in_var1); /* out_levels = 2x4 */
    out_levels = mxCalloc(m*no_of_levels,sizeof(double));
    
 /* dist_ptr = mxCreateDoubleMatrix(n,no_of_levels,mxREAL);
    dist = mxGetPr(dist_ptr); /* dist = n x no_of_levels */
    dist = mxCalloc(n*no_of_levels,sizeof(double));
    
 /* in_var2 = mxCreateDoubleMatrix(no_iter,1,mxREAL);
    final_ave_dist = mxGetPr(in_var2); /* final_ave_dist 100x1; stores each ave_dist of the iterations */
    final_ave_dist = mxCalloc(no_iter,sizeof(double));
    
 /* in_var3 = mxCreateNumericArray(ndim,dims,mxDOUBLE_CLASS,mxREAL);
    final_out_levels = mxGetPr(in_var3); /* final_out_levels 2x4x100; stores out_levels in each iteration */
    final_out_levels = mxCalloc(m*no_of_levels*no_iter,sizeof(double));
    
 /* in_var4 = mxCreateDoubleMatrix(n,no_iter,mxREAL);
    final_assignment = mxGetPr(in_var4); /* final_assignment n x 100 (n = no.of.customers)*/
    final_assignment = mxCalloc(n*no_iter,sizeof(double));
    
/* min_dist_ptr = mxCreateDoubleMatrix(n,1,mxREAL);
min_dist = mxGetPr(min_dist_ptr); /* min_dist = min(dist,[],2) n x 1 */
    min_dist = mxCalloc(n,sizeof(double));
    
/* min_ind_ptr = mxCreateDoubleMatrix(n,1,mxREAL);
min_ind = mxGetPr(min_ind_ptr); /* min_ind = min(dist,[],2) n x 1 */
min_ind = mxCalloc(n,sizeof(double));
    
/* mapp_ptr = mxCreateDoubleMatrix(n,1,mxREAL); /* Q x 1 (SIZE OF Q UNKNOWN AS USED FOR SELECTING MATCHING INDICES) */
/* mapping = mxGetPr(mapp_ptr); /* but initialized with size n x 1 */
    mapping = mxCalloc(n,sizeof(double));
    
/* rand_ptr1 = mxCreateDoubleMatrix(1,no_of_levels,mxREAL);
    randoms1 = mxGetPr(rand_ptr1); /* randoms1 = 1 x no_of_levels */
    randoms1 = mxCalloc(no_of_levels,sizeof(double));
    
/* rand_ptr2 = mxCreateDoubleMatrix(m,1,mxREAL);
    randoms2 = mxGetPr(rand_ptr2); /* randoms2 = m x 1 */
    randoms2 = mxCalloc(m,sizeof(double));
    
    
    /*---------------- Main Kmeans For-Loop starts here -----------------*/
    for (iter = 0; iter < no_iter; iter++)
    {
        mexPrintf("Iteration = %d\n",iter+1);
        if(First_Run == 1) /* Learning Mode = 1 */
        {
    /* --------------- OUT_LEVELS CALCULATION PART ------------------------*/
                        
            /* rep_ptr = mxCreateDoubleMatrix(1,no_of_levels,mxREAL);
            tmpreps = mxGetPr(rep_ptr); */
            for(i = 0; i < m; i++)
            {
                /*for (j = 0; j < 4; j++)
                { */
                    random_generator(1,no_of_levels,randoms1);
                    max_val[0] = fnmax(input_train,m,n,2,i);
                    min_val[0] = fnmin(input_train,m,n,2,i);
                                        
                    /* rep_mat(min_val[0],1,no_of_levels,tmpreps); */
                    for(k = 0; k < no_of_levels; k++)
                    {
                        randoms1[k] = randoms1[k] * (max_val[0] - min_val[0]);
                        out_levels[(i) + (k*m)] = randoms1[k] + min_val[0];
                    }
                /*} */
            }
        }
    /* --------------------------------------------------------------------- */
        else /* Learning Mode = 0 */
        {
    /* --------------- LOADING XK_BASE PART FOR OUT_LEVELS ----------------- */
            pmat = matOpen(file, "r");
            if (pmat == NULL)
            {
                mexPrintf("Error reading file %s\n", file);
                mexErrMsgTxt("Check the filename\n");
                /*return(EXIT_FAILURE); */
                /*return;*/
            }
            in_Xk_Base = matGetVariable(pmat, "Xk_Base");
            if (in_Xk_Base == NULL)
            {
                /* mexPrintf("Error reading existing matrix Xk_Base\n"); */
              mexErrMsgTxt("Error reading existing matrix Xk_Base\n");
                /*return; */
            }
            Xk_Base = mxGetPr(in_Xk_Base);
            memcpy(out_levels,Xk_Base,m*no_of_levels*sizeof(double));
            matClose(pmat);
    /* --------------------------------------------------------------------- */
        }
        ave_dist_old = 1; ave_dist_new = 2;
   /* tmp = ave_dist_old - ave_dist_new;
        if(tmp < 0)
        {
            tmp = -1.0000 * tmp;
        } */

        while((fabs(ave_dist_old - ave_dist_new) * 100)/ ave_dist_old >= 0.01) /*while((tmp * 100)/ave_dist_old >= 0.01) */
        {
            ave_dist_old = ave_dist_new;
      /* Distance function */
            distance(input_train,m,n,out_levels,y,dist);

      /*------ Finding the minimum of Dist and the index -------------------*/
                       
           /* for( i = 0; i < n; i++){
                tmp = dist[i + j*n];
                for(j = 0; j < y; j++){
                   if(dist[i + j*n] < tmp){
                       tmp = dist[i + j*n];
                       min_dist[i] = tmp;
                       min_ind[i] = j;
            * }}} */
            for(i = 0; i < n; i++)
            {
                tmp = dist[i];
                /* mexPrintf("dist[%d][%d] = %f\n",i,0,dist[i*y + 0]); */
                for(j = 0; j < y; j++)
                {
                   if(dist[(i) + (j*n)] <= tmp)
                   {
                      /* mexPrintf("dist[%d][%d] = %f\n",i,j,dist[i + j*n]); */
                       tmp = dist[(i) + (j*n)];
                       min_dist[i] = tmp;
                       min_ind[i] = j;
                   }
                }
            }
       /*-------------------------------------------------------------------*/
            k = 0;
            
            for (i = 0; i < no_of_levels; i++)
            {
                cnt = 0;
                for(j = 0; j < n; j++)
                {
                    if(min_ind[j] == i)
                    {
                        mapping[cnt] = j; /* getting the index of min(dist,[],2) */
                        cnt++ ;
                    }
                }
                
                if(cnt == 0)
                {
                    random_generator(m,1,randoms2);
                    max_val[0] = fnmax(input_train,m,n,2,1);
                    max_val[1] = fnmax(input_train,m,n,2,2);
                    min_val[0] = fnmin(input_train,m,n,2,1);
                    min_val[1] = fnmin(input_train,m,n,2,2);
                    
                    for(j = 0; j < m; j++)
                    {
                        randoms2[j] = randoms2[j] * (max_val[j] - min_val[j]);
                        /* rep_mat(min_val[k],n,1,tmpreps); */
                        out_levels[k] = randoms2[j] + min_val[j];
                        k++;
                    }
                }
                else
                {
                    
                    for(ii = 0; ii < m; ii++)
                    {
                        for(j = 0; j < cnt; j++)
                        {
                           w = (int) mapping[j];
                           sum = sum + input_train[(ii) + (w*m)];
                        }
                        avg = sum/cnt;
                        out_levels[k] = avg;
                        k++ ; avg = 0; sum = 0;
                    }
                }
            }
            /*ave_dist_new = mean(min_dist); */
            sum = 0;
            for(i = 0; i < n; i++)
            {
                sum = sum + min_dist[i];
            }
            ave_dist_new = sum / n;

/* tmp = ave_dist_old - ave_dist_new;
if(tmp < 0)
{
tmp = -1.0000 * tmp;
} */

        } /* End of WHILE loop */
        
        final_ave_dist[iter] = ave_dist_new;
mexPrintf("ave_dist_new in iter %d = %f\n",iter,ave_dist_new);
        mexPrintf("final_ave_dist[%d] = %f\n",iter,final_ave_dist[iter]);
        /* final_assignment(:,iter) = min_ind; */
        for(i = 0; i < n; i++)
        {
            final_assignment[(i) + (n*iter)] = min_ind[i];
        }
        
        /* final_out_levels(:,:,iter) = out_levels; */
        
        for(i=0; i < m; i++)
        {
            for(j=0; j < no_of_levels; j++)
            {
                final_out_levels[(i) + (j*m) + (no_of_levels*m*iter)] = out_levels[(i) + (j*m)];
                /* y++; */
            }
        }
    }/* end of for loop for iter */
    
    
    /* Finding min(final_ave_dist)
       double min_over_all_iter;
       int min_ind_over_all_iter; */
    tmp = final_ave_dist[0];
    for(i = 0; i < no_iter; i++)
    {
        if(tmp > final_ave_dist[i])
        {
            tmp = final_ave_dist[i];
            min_over_all_iter = final_ave_dist[i];
            min_ind_over_all_iter = i;
        }
    }
    
    /* Final Outputs put into respective output variables. */
    for(i = 0; i < n; i++)
    {
        assignment[i] = final_assignment[(i) + (min_ind_over_all_iter*n)];
        all_ave_dist[i] = final_ave_dist[i];
    }
    ave_dist[0] = min_over_all_iter;
    
    for(i = 0; i < m; i++)
    {
        for(j = 0; j < no_of_levels; j++)
        {
            Xk[(i) + (j*m)] = final_out_levels[(i) + (j*m) + (min_ind_over_all_iter * no_of_levels * m)];
        }
    }
    
    /* mexPrintf("Reached the END\n"); */
    /* Clearing all the local variables\arrays used */
/* mxSetData(in_var1,NULL); mxSetData(in_var2,NULL); mxSetData(in_var3,NULL); mxSetData(in_var4,NULL);
    mxDestroyArray(in_var1); mxDestroyArray(in_var2); mxDestroyArray(in_var3); mxDestroyArray(in_var4);
    
    mxSetData(dist_ptr,NULL); mxSetData(rand_ptr1,NULL); mxSetData(rand_ptr2,NULL);
  mxDestroyArray(dist_ptr); mxDestroyArray(rand_ptr1); mxDestroyArray(rand_ptr2);
    
    mxSetData(min_dist_ptr,NULL); mxSetData(min_ind_ptr,NULL); mxSetData(mapp_ptr,NULL);
  mxDestroyArray(min_dist_ptr); mxDestroyArray(min_ind_ptr); mxDestroyArray(mapp_ptr); */

    mxFree(out_levels); mxFree(dist); mxFree(final_ave_dist); mxFree(final_out_levels); mxFree(final_assignment);
    mxFree(randoms1); mxFree(randoms2); mxFree(min_dist); mxFree(min_ind); mxFree(mapping);
    
    if(First_Run == 0){
        mxSetData(in_Xk_Base,NULL);
        mxDestroyArray(in_Xk_Base);
}
/* End of Mex_Kmeans */
}

Please let me know, where all have I gone wrong.
> Hari

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us