% Function VQ_ENCODE: Coding of given vector
%    by known codebook
%
% Usage: [idx,dist]=vq_encode(X,C) ;
%
% Input parameters:
%   X   - matrix with realizations of analyzed data 
%         (particular realizations are in rows)
%   C   - matrix of codebook 
%         (particular vectors of the codebook are in rows)
%
% Output parameters:
%   idx  - indices of the nearest codebook element related to each realization
%   dist - distances between each realization and the nearest codebook element

%                 Made by Petr Pollak, 1 Dec 2016


function [idx,dist]=vq_encode(X,C) ;



Cnum=size(C,1) ;
Csize=size(C,2) ;

Xnum=size(X,1) ;
Xsize=size(X,2) ;

if Xsize ~= Csize,
    error('ERROR: Number of columns in variables X and C must be same!') ;
end

sumd=zeros(1,Xnum);
idx=zeros(1,Xnum);

for ii=1:Xnum,
    
   Xsample = X(ii,:) ;
   
   DD=[];
   for jj=1:Cnum,

       % Euclidan distance is used 
       DD = [DD; sqrt(sum((Xsample-C(jj,:)).^2))] ;
       
   end
       
   [dist(ii),idx(ii)]=min(DD) ;
   
end

