% This uses multiplicative algorithm to solve the optimal design with A-criterion for a
% general coefficient matrix K
%
% Jan 12, 2012

function [w fval] = multiplicativec(M,K,w0,freq,tol,maxiter)

n = sqrt(size(M,1));
M = rearrange(M);
blk{1,1} = 's';
blk{1,2} = n;

w = w0;

[V,D] = svd(smat(blk,M*w));
invX = V*diag(diag(D).^(-1))*V';
KtinvX = K'*invX;
swd = trace(KtinvX*K);
iK = KtinvX'*KtinvX/swd;
iter = 1;

while iter < maxiter
  
  dw = M'*svec(blk,iK);
  
  if mod(iter,freq)==0
    fprintf('iter fval sumw minw term1 %g %g %g %g %g\n', iter, trace(KtinvX*K), sum(w), min(w), max(dw))
  end
  
  if max(dw) <= (1 + tol)   
    break
  end
  
  w = w.*dw;
  
  [V,D] = svd(smat(blk,M*w));
  invX = V*diag(diag(D).^(-1))*V';
  KtinvX = K'*invX;
  swd = trace(KtinvX*K);
  iK = KtinvX'*KtinvX/swd;
  
  iter = iter + 1;
  
end

D = svd(KtinvX*K);
fval = sum(D);
fprintf(' termination: iter, fval %g, %g\n',  iter, fval)