function [sv,ycanon,xcanon,coeff] = pls(X,Y,stdize)

// Intercorrelations analysis

// X ... data matrix arranged as columns - variables and rows - observations
// Y ... the other group arranged accordingly
// stdize 0 ... made on standardized data (default)
//        1 ... analysis on centered data

// coeff ... coefficients (singular vectors) - columns correspond to individual
// canonical variables, the Y coefficients below X ones
// xcanon ... X canonical variables - linear combinations
// ycanon ... Y canonical variables - linear combinations
// sv ... singular values

// Literature: Wegelin, J.A. (2000). A survey of partial least squares methods,
// with emphasis on the two-block case. Technical report No. 371, University
// of Washington: Seattle

// Copyright (C): Lukáš Malec and Jaroslav Poživil;
// University of Business in Prague, Czech Republic
// Date: $2016-01-05$

[lhs,rhs]=argn(0)

[n,nc] = size(X), [m,mc] = size(Y)

if n <> m then
    error(msprintf(gettext("%s: The No. of observations must be equal in...
 both sets\n"),"Error"))

end

if rhs==2
    X = wcenter(X,'r'), Y = wcenter(Y,'r')
    Cxy = X'*Y/(n - 1)

elseif stdize==1 then
    Xm = mean(X,'r'), Ym = mean(Y,'r')
    X = X - Xm(ones(n,1),:)
    Y = Y - Ym(ones(n,1),:)
    Cxy = X'*Y

elseif stdize==0 then
    X = wcenter(X,'r'), Y = wcenter(Y,'r')
    Cxy = X'*Y/(n - 1)

end

[U,S,V] = svd(Cxy)

md = min(nc,mc), coeff = [U(:,1:md);V(:,1:md)]

for i = 1:md
    p = find((coeff(:,i)<0))
  if length(p) > (nc + mc)/2 then
    coeff(:,i) = -coeff(:,i)
    U(:,i) = -U(:,i), V(:,i) = -V(:,i)

  end
end

xcanon = X*U(:,1:md), ycanon = Y*V(:,1:md)
sv = diag(S)

endfunction
