%% Fuzzy_Paper Implementation : 
%  IEEE TRANSACTIONS ON FUZZY SYSTEMS, VOL. 20, NO. 4, AUGUST 2012
%  ---------------------------------------------------------------
%  Training : The membership Function learning Algorithm 
%  -----------------------------------------------------

function [OldC2, OldSig2, OldD2] = modularlearning(X, Y, C, Sig)

% close all; 
eta = 0.01;          % Learning Parameter 
sigma = 0.05;       % Parameter Reducing Factor 
maxiter = 5;       % Maximum Number of Iterations 
% sig = 1.0;          % Data distributed varrience 

% Initialize Sig Matrix
% Sig = repmat(sig, param.dict_size, param.lDim);

A = computeA(X, C, Sig); 
D = (A'*A)\(A'*Y);

OldEx = computeError(X, Y, C, Sig, D); 
disp(['[Itrn : ' num2str(0) '] [Err : ' num2str(OldEx) ']']);

t = 0;
OldC = C;
OldSig = Sig; 
OldD = D;

OldC2 = C; 
OldSig2 = Sig;
OldD2 = D;

while t < maxiter
    t = t + 1;
    [ErDrvtC, ErDrvtSig] = computeErrorDrvt(X, Y, OldC, OldSig, OldD);

    NewC = OldC - eta*ErDrvtC; 
    NewSig = OldSig - eta*ErDrvtSig/5; 

    OldC = NewC; 
    OldSig = NewSig; 

    A = computeA(X, NewC, NewSig); 
    OldD = (A'*A)\(A'*Y);
    
    NewEx = computeError(X, Y, NewC, NewSig, OldD);
    disp(['[Itrn : ' num2str(t) '] [Err : ' num2str(NewEx) ']']);
    if NewEx < OldEx 
        OldEx = NewEx;
        OldC2 = NewC; 
        OldSig2 = NewSig;
        OldD2 = OldD; 
        disp(['[Err : ' num2str(OldEx) ']']);
    end

end



