function [D,alpha]=Metaface_rand(X,p,lambda,Jstep_T,Max_iteration)
% output:D an dictionary we want to learn with size of m by p
% input :X denote the dataset matrix with size of m by n
% image: every column of X denote one image
% lamba: denote a coeff of l1_ls
% the formula is that : J= argmin(D,alpha){norm(X-D*alpha,2)^2+lamta*norm(alpha,1)}


Jnow=10;Jpre=0;Dnow=zeros(size(X,1),p);
%initialize D begin
numcomps=p;
% build random P
P=randn(size(A,1),numcomps);
for i=1:numcomps
   P(:,i)=P(:,i)./norm(P(:,i));
end

D=P;

%initialize D end

error=[];iteration=0;
while abs(Jnow-Jpre)>Jstep_T&& iteration < Max_iteration
    fprintf(['Metaface:steperror=' num2str(Jnow-Jpre) ';and iteration=' num2str(iteration) '.\n']);
% Fix D
for i=1:n
    [s,status] = l1_ls(D, X(:,i), lambda,1e-3,true);
    if sum(status=='Solved')~=6
    fprintf('l1 optimation can not get the result!!!');
    end
    alpha(:,i)=s;
end
%optimation one column by one begin

zz=X-D*alpha;zalpha=alpha(:);
J_ls=zz(:)'*zz(:)+lambda*sum(abs(zalpha(:)))

% Fix alpha, update D. begin
for i=1:p
   ai=alpha(i,:);
   Y=X-D*alpha+D(:,i)*ai;
   di=Y*ai';
   di=di./norm(di,2);
   D(:,i)=di;
end
% Fix alpha, update D. end

Jpre=Jnow;
zz=X-D*alpha;zalpha=alpha(:);
Jnow=zz(:)'*zz(:)+lambda*sum(abs(zalpha(:)))
iteration=iteration+1;
% Dpre=Dnow;Dnow=D;
% error=[error Jnow]
% Jnow-Jpre
% max(max(abs(Dnow-Dpre)))
% plot(error,'rs');
% keyboard;
end
