MATLAB: How to use C++ to speed up the matlab code

cimage processingmatlab functionspeed

Hi every one, I am working on image processing and I generated a matlab code with many for loops, it takes too long to display results, can any one please tell how can I speed it up using C++ ?
thank you !

Best Answer

Sorry, I cannot resist :-)
MyCorrCoeff2 can still be improved by considering the columnwise storing of elements in arrays. The normalization happens repeatedly inside the inner loops, so it is cheaper to compute it once outside the loops:
function H = MyCorrCoeff3(Mat)
% Author: Jan Simon, License: CC BY-SA 3.0
c = size(Mat,1);
nc = (0.5 * c * (c + 1));
H = ones(nc, nc); % Pre-allocate!!!
MP = permute(Mat, [3, 2, 1]);
MP = MP - sum(MP, 1) / size(MP, 1);
% MP = bsxfun(@minus, MP, sum(MP, 1) / size(MP, 1));
CovN = squeeze(sqrt(sum(MP .* MP, 1)));
jH = 1;
for i = 1:c
for j = i:c
cov1 = MP(:, j, i);
cov1n = CovN(j, i);
iH = 1;
for d = 1:c
for l = d:c
if iH < jH % Use symmetry of H
% Emulate: r = cov([Mat(i, j, :), Mat(d.l,:)]);
r21 = (MP(:, l, d).' * cov1) / cov1n / CovN(l, d);
H(iH, jH) = r21;
H(jH, iH) = r21;
end
iH = iH + 1; % Update indices related to H:
end
end
jH = jH + 1;
end
end
H(isnan(H)) = 0;
0.085 sec, 38 times faster than the original version. :-)
[07-Apr-2017 16:34 UTC] Enough for today. Now the code is in a form which could profit from C-coding. The bottleneck is still with about 85% of the total time:
r21 = (MP(:, d, l).' * cov1) / cov1n / CovN(d, l);
The vector multiplication is calculated in an optimized BLAS-library already. Therefore I think you can reduce the time for the overhead of calling the library and some percent of the loops only, perhaps 10%. It will be more useful to try a parallelization with PARFOR.