function [A_kmda A_kmuda] = KMUDA(CK_multiview,Label_multiview,kla,num_class,num_classtrain)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CK_multiview: multiview train centered kenel matrces, each view
% corresponds to one cell;
% Label_multiview: class label of X_multiview, type: num;
% each view has the same number of classes;
% kla: tunable coefficient
% num_class: class number
% num_classtrain: the number of training samples in each class
% A_kmuda: multiple view-specific transforms, one for each view;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

nV = length(CK_multiview);
Sb = cell(nV,1);
St = cell(nV,1);
Lamda = kla;

N = num_class * num_classtrain;
total_N = nV * N;

% construct matrix W = [Wl], Wl = [1/nl]
W = zeros(N,N);
for i = 1:num_class
    W(num_classtrain*(i-1)+1:num_classtrain*i,num_classtrain*(i-1)+1:num_classtrain*i) = 1/num_classtrain;
end

% construct matrices Sb, St
for i = 1:nV
    Sb{i,1} = CK_multiview{i,1} * W * CK_multiview{i,1};
    Sb{i,1} = (Sb{i,1} + Sb{i,1}')/2;
    St{i,1} = CK_multiview{i,1} * CK_multiview{i,1};
    St{i,1} = (St{i,1} + St{i,1}')/2;
end

%construct matrice Cij
for i = 1:nV
    alignCol{i,1} = CK_multiview{i,1};
end

sA = zeros(total_N,total_N);
sB = zeros(total_N,total_N);

Mult = zeros(nV,1);
Mult(1) = 1;
for i = 2:nV
    Mult(i) = 1/trace(St{i,1});
    for j = 1:i-1
        Mult(i) = Mult(i) * trace(St{j,1});
    end
   for k = i+1:nV
       Mult(i) = Mult(i) * trace(St{k,1});
    end
end

for r = 1:nV
    for c = r:nV
        rs = N*(r-1)+1;
        re = N*r;
        cs = N*(c-1)+1;
        ce = N*c;
        if r == c
            sA(rs:re,cs:ce) = Sb{r,1};
            sB(rs:re,cs:ce) = St{r,1}*Mult(i)+0.00001*eye(N);%nonsingularity  
        else
            tmp = alignCol{r,1}*alignCol{c,1}*Lamda;
            sA(rs:re,cs:ce) = tmp;
            sA(cs:ce,rs:re) = tmp';
        end
    end
end

%% get a_mulda
%C = max(kN);
L = num_class-1;
%L = K;

%L = 5;
% initiate w1,D{i,1}
[V E] = eigs(sA,sB,L);
for i =1:nV
    D{i,1} = [];
    D{i,1} = V(N*(i-1)+1:N*i,:); %mlda
    D_mu{i,1} = [];
    D_mu{i,1} = V(N*(i-1)+1:N*i,1); %mulda
end
% get other wi
PP = [];
for i = 2:L
    for j = 1:nV
        Tmp = D_mu{j,1}'*St{j,1}*D_mu{j,1};
        Pj = eye(N)-St{j,1}*D_mu{j,1}*inv(Tmp)*D_mu{j,1}';
        js = N*(j-1)+1;
        je = N*j;
        PP(js:je,js:je) = Pj;
    end
    sA = PP*sA;
    [V E] = eigs(sA,sB,1);
    for r = 1:nV
        D_mu{r,1} =[D_mu{r,1} V(N*(r-1)+1:N*r,1)];
    end
end
for i = 1:nV
    A_kmda{i,1} = D{i,1};  %mlda
    A_kmuda{i,1} = D_mu{i,1};  %mulda
end
fprintf('KMUDA finished\n');





    