
disp(['start learning from example ' num2str(this)]); tic
for (orient = 1 : numOrient)
       Ccopy(SUM1map0{1, orient}, SUM1map{this, orient}, sizex, sizey); 
end
deformedTemplate0{1} = single(zeros(sizex, sizey));
CsharedSketch(numOrient, locationShiftLimit0, orientShiftLimit0, subsample, ... % about active basis  
       numElement, numImage0, sizex, sizey, SUM1map0, ... % about training images 
       halfFilterSize, Correlation, allSymbol(1, :), ... % about filters
       numStoredPoint, storedlambda, storedExpectation, storedLogZ, ... % about exponential model 
       selectedOrient, selectedx, selectedy, selectedlambda, selectedLogZ, ... % learned parameters
       commonTemplate, deformedTemplate0); % learned templates 
%% Iteration part 1: search nearest neighbors by template matching
for (it = 1 : numIteration)
close all; 
CgetSUM2(numOrient, subsample, ... % about active basis  
      numElement, numImage, sizex, sizey, MAX1map, ... % about training images 
      selectedOrient, selectedx, selectedy, selectedlambda, selectedLogZ, ...% learned parameters
      SUM2score) % output template matching score
[SUM2scoreSort ind] = sort(SUM2score, 'descend'); 
for (k = 1 : numNeighbor)
     neighbork = ind(k); 
     for (orient = 1 : numOrient)
       Ccopy(SUM1mapLearn{k, orient}, SUM1map{neighbork, orient}, sizex, sizey); 
     end
end
%% Iteration part 2: re-learn the template from nearest neighbors
CsharedSketch(numOrient, locationShiftLimit, orientShiftLimit, subsample, ... % about active basis  
       numElement, numNeighbor, sizex, sizey, SUM1mapLearn, ... % about training images 
       halfFilterSize, Correlation, allSymbol(1, :), ... % about filters
       numStoredPoint, storedlambda, storedExpectation, storedLogZ, ... % about exponential model 
       selectedOrient, selectedx, selectedy, selectedlambda, selectedLogZ, ... % learned parameters
       commonTemplate, deformedTemplate); % learned templates 
%% Iteration part 3: store learned template and its neighbors
if (it==numIteration)
    meanSUM2score(this, 1) = mean(SUM2scoreSort(1:numNeighbor)); 
    allSUM2score(this, :) = SUM2score; 
    neighbor(this, :) = ind(1:numNeighbor); 
    allTemplate{this} = commonTemplate+0.; 
    allSelectedOrient(this, :) = selectedOrient + 0.;  
    allSelectedx(this, :) = selectedx + 0.; 
    allSelectedy(this, :) = selectedy + 0.;     
    allSelectedlambda(this, :) = selectedlambda + 0.; 
    allSelectedLogZ(this, :) = selectedLogZ + 0.; 
    OutThis; 
end
end  % end of it
disp(['learning time: ' num2str(toc) ' seconds']);
