function [T] =  lowrankT(T, F)
% T: init. T  (Identiy matrix is a good choice, or a leaned one for online learning
% F: training data (one class per cell)

K = length(F);
alpha = 0.02; % learning rate
eigThd = 0.005; 
lambda = 1/K; % fixed
MaxIter = 99;
plotopt=0;
% cnorm = 1; % can be dropped
dim = size(F{1}, 1); % dim reduction is experimental

F{K+1}=[];
for i=1:K
    F{K+1}=[F{K+1} F{i}];
end

%% Training of T
D = size(F{1},1);
T_rank = D;

if isempty(T)
    T = eye(T_rank); 
    %     T = cnorm*(T/norm(T));
end

T = T(1:dim, :);
threshold = 1e-6;
zz = 1;

textprogressbar('learning transformation: ');

while(true)
    
    T_prev = T;
    Obj_sub1 = NaN(1, K); 
    Grd_sub1 = NaN(dim, T_rank, K); 
    
    Obj_sub3 = NaN(1, 1);
    Grd_sub3 = NaN(dim, T_rank, 1); 
    
    for k = 1:K
        [m, n]=size(T*F{k});
        [U, Sigma, V] = svd((T*F{k}), 'econ');
        Obj_sub1(k) = sum(diag(Sigma));
        F_rank=min([m,n]);        
        r = sum(diag(Sigma)<=eigThd); 
        if r==0
            r=r+1;
        end
        if F_rank-r==0
            r=r-1;
        end
        RndMat = orth(rand(r, r))*diag(rand(r, 1))*orth(rand(r, r))';
        U1 = U(:, 1:end-r);
        V1 = V(:, 1:end-r);
        U2 = U(:, end-r+1:end); 
        V2 = V(:, end-r+1:end); 
        W = U2*RndMat*V2';
        UU=U1*V1';
        Grd_sub1(:,:,k) = (UU + W)*(F{k})';
        
    end
    
    [m, n]=size(T*F{K+1});
    [U3, Sigma3, V3] = svd((T*F{K+1}), 'econ');
    
    Obj_sub3(1) = sum(diag(Sigma3));    
    F_rank3=min([m,n]);    
    r3 = sum(diag(Sigma3)<=eigThd);
    if r3==0
        r3=r3+1;
    end
    if F_rank3-r3==0
        r3=r3-1;
    end
    
    RndMat3 = orth(rand(r3, r3))*diag(rand(r3, 1))*orth(rand(r3, r3))';
    U1_3 = U3(:, 1:end-r3);  
    V1_3 = V3(:, 1:end-r3);  
    U2_3 = U3(:, end-r3+1:end);  
    V2_3 = V3(:, end-r3+1:end);  
    W_3 = U2_3*RndMat3*V2_3';
    UU_3=U1_3*V1_3';
    Grd_sub3(:,:,1) = (UU_3 + W_3)*(F{K+1})';
    
    
    %% Evaluate Objective function
    Obj_1 = 1/K * sum(Obj_sub1);
    Obj_3 = 1/1 * sum(Obj_sub3);
    Obj_all = Obj_1 - lambda*Obj_3;
    Obj_all_plot(zz) = Obj_all;
    zz = zz+1;
    
    textprogressbar(zz);

    if plotopt
        disp([zz Obj_all]);
    end

    Grd_1 = 1/K * sum(Grd_sub1, 3);
    Grd_3 = 1/1 * sum(Grd_sub3, 3);
    Grd_all = Grd_1  - lambda*Grd_3;

    T = T - alpha*Grd_all;
    % T = cnorm*(T/norm(T));
    
    
    diff = sum(sum((T_prev-T).^2));
     if (zz>MaxIter)
        break
    end
    
    
end

textprogressbar('done');

if plotopt
    figure
    plot(1:zz-1, Obj_all_plot)
    xlabel('Number of Iterations')
    ylabel('Objective Function')
end
