I am converting an implementation of an image segmentation method from C++ to Matlab.
It is an iterative method that that make calls to two functions: em() and mpm(). Those two functions uses two reasonably big auxiliary matrices, so to avoid reallocating memory at every call in my C++ implementation, I have prealocated the memory for the matrices and reseted its values when it was necessary.
How can I avoid memory reallocation in the Matlab implementation? As far as I know, pre-allocating the matrices won't solve my problem because when a function tries to change the values of an argument, Matlab automatically creates a copy of it.
Is it possible to declare a variable that is shared by all functions inside a M file?
Edit:
Here's an outline of my C++ code. The two matrices that I preallocate are chanceMatrix
and labelAssignedVector
:
GSegmentedImage * GEmMpmSegmentator::segmentImage(GImage * image, int labelRange, int steps, unsigned char minGrayLevel){
GSegmentedImage * segmentedImage = new GSegmentedImage(image->getHeight(), image->getWidth());
GParameterVector * paramVector = new GParameterVector(labelRange);
randomizeLabelField(segmentedImage, labelRange);
setOutOfImageLabel(segmentedImage, image, minGrayLevel);
initializeParameterVector(image, paramVector);
// labelAssignedVector stores how many times a pixel received a label 'k'.
// row = image row, column = image column, page = label.
G3DMatrix<unsigned char> * labelAssignedVector = new G3DMatrix<unsigned char>(image->getHeight(), image->getWidth(), labelRange);
// Chance matrix is used by the mpm method.
// chanceMatrix: row = label, column = gray level, page = number of different neighbors
G3DMatrix<double> * chanceMatrix = new G3DMatrix<double>(paramVector->getLabelRange(), 256, 9);
for (int i = 0; i < steps; i++){
labelAssignedVector->reset();
if (difPenalty < difMax){
difPenalty += difInc;
}
mpm(paramVector, labelAssignedVector, segmentedImage, image, minGrayLevel, chanceMatrix);
em(paramVector, labelAssignedVector, image);
}
delete paramVector;
return segmentedImage;
}