Optimization of variable-length array

7 views (last 30 days)
Alessandro Masullo
Alessandro Masullo on 23 Oct 2015
Hello,
I'm trying to optimize a code where I have an array with unknown size and I'm not sure about two solutions that I have in mind.
In brief, I have an image and I want to extract some features from it. I don't know how many features I can extract from the image, so I allocate the initial memory of the features array as the maximum number of features that can be extracted. The problem is that the features are extracted from different regions of interest, and each of them has an inner loop, and I'm not sure how is the correct way of updating the initial vector. I'll show two examples with some pseudo-code:
nFeature = 1e6;
feature = zeros(nFeature,1);
iFeature = 0;
for i = 1:nROI
[newFeatures,nNewFeatures] = find_features(i);
feature(iFeature+1:iFeature+nNewFeatures) = newFeatures;
iFeature = iFeature+nNewFeatures
end
In this example, the function "find_features" finds features in the ROI of the image and the main array "feature" is updated outside the function. I like this solution because it is neat, although the function "find_features" needs to allocate more memory in its scope, because I don't know how many features can be extracted from each ROI, and this could be slow.
The alternative solution is:
nFeature = 1e6;
feature = zeros(nFeatures,1);
for i = 1:nROI
[feature,nFeature] = find_features(i,feature,nFeature);
end
In this case, the function "find_features" not only finds the features, but it also updates the vector of features. In this case, the memory is allocated just once, because the features found by find_features are automatically appended to the main vector feature. I find this solution more "dirty" because the huge array of features is being passed many times to the function "find_features". Moreover, in reality, I need to update five different arrays, so I have five more inputs besides the proper inputs of "find_features".
Which solution should I adopt? Is there anything better that I can do?
Thank you.

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!