function acc = libsvmcrossval_ova_pca(y, X, opts, nfold)
    if nargin < 3, opts = ''; end
    if nargin < 4, nfold = 10; end
    
        rng(0,'twister'); % begin from the same numbers for random samples generation
        cv = cvpartition(y, 'kfold',nfold);          %# Statistics toolbox
        indices = zeros(size(y));
        for i=1:nfold
            indices(cv.test(i)) = i;
        end
    
%         indices = crossvalidation(y, nfold); end

    %# N-fold cross-validation testing
    acc = zeros(nfold,1);
    for i=1:nfold
        testIdx = (indices == i); trainIdx = ~testIdx;
        ptr=X(trainIdx,:);
        mitr=min(ptr); matr=max(ptr);
        ptrnorm=(ptr-repmat(mitr,size(ptr,1),1))./(repmat(matr,size(ptr,1),1)-repmat(mitr,size(ptr,1),1));
        pte=X(testIdx, :);
        ptenorm=(pte-repmat(mitr,size(pte,1),1))./(repmat(matr,size(pte,1),1)-repmat(mitr,size(pte,1),1));
        
        [pc,score,latent,tsquare,explained] = princomp(ptrnorm);
        ptrpca=score(:,1:10);
        ptepca=ptenorm*pc(:,1:10);
        ptepca=ptepca-repmat(mean(ptepca),size(ptepca,1),1);
    
        mdl = libsvmtrain_ova(y(trainIdx), ptrpca, opts);
        [~,acc(i)] = libsvmpredict_ova(y(testIdx), ptepca, mdl);
%         mdl = libsvmtrain_ova(y(trainIdx), X(trainIdx,:), opts);
%         [~,acc(i)] = libsvmpredict_ova(y(testIdx), X(testIdx,:), mdl);
    end
%     acc = mean(acc);    %# average accuracy
end
function mdl = libsvmtrain_ova(y, X, opts)
    if nargin < 3, opts = ''; end

    %# classes
    labels = unique(y);
    numLabels = numel(labels);

    %# train one-against-all models
    models = cell(numLabels,1);
    for k=1:numLabels
        models{k} = libsvmtrain(double(y==labels(k)), X, strcat(opts,'-b 1 -q'));
    end
    mdl = struct('models',{models}, 'labels',labels);
end
function [pred,acc,prob] = libsvmpredict_ova(y, X, mdl)
    %# classes
    labels = mdl.labels;
    numLabels = numel(labels);

    %# get probability estimates of test instances using each 1-vs-all model
    prob = zeros(size(X,1), numLabels);
    for k=1:numLabels
        [~,~,p] = libsvmpredict(double(y==labels(k)), X, mdl.models{k}, '-b 1 -q');
        prob(:,k) = p(:, mdl.models{k}.Label==1);
    end

    %# predict the class with the highest probability
    [~,pred] = max(prob, [], 2);
    %# compute classification accuracy
    acc = mean(pred == y);
end