function kv = veckern( kernel )
%VECKERN Vectorizes a pth-order triangular kernel in a non-redundant 
%representation whose elemens are ordered according to their multi-indices
%in a lexicographical fashion.
%
%   kv = VECKERN(kernel) returns the vectorized representation of kernel,
%   which is a p-way hypercubic array (storing a triangular kernel, ie,
%   such that kernel(k1,...kp) ~= 0 only if k1 <= k2 <= ... <= kp).
%
%   See also VFILTER
%
%   CBVK Toolbox
%   JHMG, PMSB 2016

% Kernel dimensions and order
dims = size(kernel);
N = dims(1);
p = length(dims);

% Length of vectorized kernel
Nv = nchoosek(N+p-1,p);

% Sequentially fetching elements
kv = zeros(1,Nv);
inds = ones(1,p);
for n=1:Nv
    kv(n) = kernel(mysub2ind(dims,inds));
    inds = nextinds(inds-1,N)+1;
end
