function wvarx = limo_winvar(x,percent)

% function wvarx = limo_winvar(x,percent)
%
% Computes the winsorised variance along the last dimension of a 3D matrix.
% x is a matrix with EEGLAB format electrodes x frames x trials. 
% percent must be a number between 0 & 100 - default value = 20;
%
% See also LIMO_YUEN_TTEST
% ------------------------------
%  Copyright (C) LIMO Team 2019

% Original code provided by Prof. Patrick J. Bennett, McMaster University
% made 3D: GAR - University of Glasgow - 7 Dec 2009

if nargin<2;percent=20;end

if isempty(x)
    error('winvareeg:InvalidInput', 'data vectors cannot have length=0');
end

if (percent >= 100) || (percent < 0)
    error('winvareeg:InvalidPercent', 'PERCENT must be between 0 and 100.');
end

% number of trials
n=size(x,3);

% number of items to winsorize and trim
g=floor((percent/100)*n);

% winsorise x
xsort=sort(x,3);
wx=xsort;
wx(:,:,1:g+1)=repmat(xsort(:,:,g+1),[1 1 g+1]);
wx(:,:,n-g:end)=repmat(xsort(:,:,n-g),[1 1 g+1]);
wvarx=var(wx,0,3);


