# Custom function call does not return a value

I have written the following code to implement a PCA algorithm. It works on standalone basis, however when I put it into a function that is called the following output is returned pca_funct[{{2,3,4},{4,5,6}},2] as opposed to the result of function evaluation. Any suggestions ?

pca_funct[X_, k_] :=
Module[{Dim, m, n, mn, ones, Cv, phi0, lambda, phi},
Dim = Dimensions[X]; m = Dim[];
n = Dim[]; (*Compute dimensions of input matrix X*)
mn = List /@ Mean[X];(*Compute column mean matrix for X and convert it into matrix form*)
ones = ConstantArray[1, {m, 1}];
X = X - ones.Transpose[mn]; (*Center columns of X around their means to get new matrix
where columns have mean zero*)
Cv = Transpose[X].X/m;(*Step 1 in algorithm. Compute covariance matrix*)
phi0 = Eigenvectors[Cv]; (*Step 2 in algorithm. Compute Eigensystem*)
lambda = Eigenvalues[Cv];
phi = phi0[1 ;; k, 1 ;; n];
phi]

X = {{2, 3, 4}, {4, 5, 6}}; k = 2;
phi = pca_funct[X, k];
phi // MatrixForm

pca_funct[{{2,3,4},{4,5,6}},2]

• what happens when you remove the "_" from the function name? also, you can't assign to an input. You are trying to write to X inside the Module. But X is passed parameter. – Nasser Feb 3 '15 at 12:22
• Further to Nasser's comment. The underscore is a special character in Mathematica, you cannot use it in names for functions etc. See 'Pattern'. – Ymareth Feb 3 '15 at 12:27
• I did that thanks, now I have this message. "RecursionLimit::reclim: Recursion depth of 1024 exceeded" I am just starting to use Mathematica. – V_W Feb 3 '15 at 12:59

You are getting a few things about Mathematica syntax wrong. First you want to not use the underscore in variable names. Also, you can't reassign X when X is your function variable. Finally you have to use [[]] to get the elements of a list.

pcafunct[X_, k_] :=
Module[{Dim, m, n, mn, ones, Cv, phi0, lambda, phi, X1},
Dim = Dimensions[X]; m = Dim[];
n = Dim[];(*Compute dimensions of input matrix X*)
mn = List /@Mean[X];
(*Compute column mean matrix for X and convert it into
matrix form*)ones = ConstantArray[1, {m, 1}];
X1 = X - ones.Transpose[mn];
(*Center columns of X around their means to get new matrix where
columns have mean zero*)
Cv = Transpose[X1].X1/m;
(*Step 1 in algorithm.Compute covariance matrix*)
phi0 = Eigenvectors[Cv];
(*Step 2 in algorithm.Compute Eigensystem*)
lambda = Eigenvalues[Cv];
phi = phi0[[1 ;; k, 1 ;; n]];
phi]

X = {{2, 3, 4}, {4, 5, 6}}; k = 2;
phi = pcafunct[X, k]
phi // MatrixForm

Remove["Global*"]
pcafunct[X_, k_] := Module[{dim, m, n, mn, X1, cv, phi0, lambda, phi},
dim = Dimensions[X];
m = dim[]; n = dim[]; (*Compute dimensions of input matrix X*)
mn = List /@ Mean[X];
X1 = X -ConstantArray[1, {m, 1}].Transpose[mn];
cv = Transpose[X1].X1/m;
phi0 = Eigenvectors[cv];
lambda = Eigenvalues[cv];
phi = phi0[[1 ;; k, 1 ;; n]];
phi
]
X = {{2, 3, 4}, {4, 5, 6}}; k = 2;
phi = pcafunct[X, k];
phi
`