I am not fully sure what you are asking for, but something like the code below will do a PCA. I’ve done some “off-line” editing so there may be bug or two, but this should otherwise work well on an y matrix
function PrincComp(y,Cov_y=[],Nvec=[])
n = size(y,2) #no. of variables
if isempty(Cov_y)
Cov_y = cov(y)
end
isempty(Nvec) && (Nvec = 1:n)
F = svd(Cov_y) #Cov_y = U*diagonal(S)*V', S[i,i] are in decreasing order
W = F.U
lambda = F.S
for i = 1:size(W,2)
if all(W[:,i] .<= 0) #switch sign if all are negative
W[:,i] = -W[:,i]
end
end
relvar = lambda/sum(lambda)
yDemean = y .- mean(y,dims=1)
pc = yDemean*W #the principal components, in descending order
lambda = lambda[Nvec]
relvar = relvar[Nvec]
W = W[:,Nvec]
pc = pc[:,Nvec] #export a selected set of pcs
return pc,relvar,W,lambda
end
You can also specify how many dimensions you want to keep (e.g. pcaOut = pca(x,K=3)) or wich is the maximum error (unexplained variance) you are willing to accept (e.g. pcaOut = pca(x,error=0.1) ) in the projected matrix - the default is 0.05