vq.m
上传用户:loeagle
上传日期:2013-03-02
资源大小:1236k
文件大小:2k
源码类别:

通讯编程文档

开发平台:

Matlab

  1. function [codebook,distortion]=VQ(training_seq,dimension,codebook_size,tolerance)
  2. %VQ.m  Vector quatizer design using K-means algorithm
  3. % [codebook,distortion]=VQ(training_seq,dimension,codebook_size,tolerance)
  4. % training_seq = training sequence
  5. % dimension = dimension of the quantizer
  6. % codebook_size = size of the codebook (rate=log2(codebook_size)/dimension)
  7. % tolerance = desired relative distortion (default=0.001)
  8. % Length of training_seq must be a multiple of the dimension of quantizer
  9. if (nargin==3)
  10.   tolerance=0.001;
  11. end
  12. m=round(length(training_seq)/dimension);
  13. if (m*dimension-length(training_seq)<0)
  14.   error('length of training_seq is not a multiple of dimension')
  15. end
  16. % initialize the codebook
  17. initial=training_seq(1:dimension*codebook_size);
  18. initialcodebook=(reshape(initial,dimension,codebook_size))';
  19. updated_codebook=initialcodebook;
  20. % first update
  21. newdistortion=0;
  22. distortion=0;
  23. for i=1:m;
  24.   training_seq_block=training_seq((i-1)*dimension+1:i*dimension);
  25.   training_matrix(i,:)=training_seq_block;
  26.   distortion_block=[ ];
  27.   for j=1:codebook_size;
  28.     distort=sum((training_seq_block-updated_codebook(j,:)).^2);
  29.     distortion_block=[distortion_block distort];
  30.   end
  31.   [distortion_min,ind]=min(distortion_block);
  32.   newdistortion=newdistortion+distortion_min;
  33.   index(i)=ind;
  34. end
  35. for l=1:codebook_size;
  36.   partition=(index==l);
  37.   if sum(partition)>0
  38.     updated_codebook(l,:)=partition*training_matrix/sum(partition);
  39.   end
  40. end
  41. newdistortion=newdistortion/m;
  42. % furthur updated until the desired tolerance is met
  43. while(abs(distortion-newdistortion)/newdistortion>tolerance)
  44.   distortion=newdistortion;
  45.   newdistortion=0;
  46.   for i=1:m;
  47.     training_seq_block=training_seq((i-1)*dimension+1:i*dimension);
  48.     training_matrix(i,:)=training_seq_block;
  49.     distortion_block=[ ];
  50.     for j=1:codebook_size;
  51.       distort=sum((training_seq_block-updated_codebook(j,:)).^2);
  52.       distortion_block=[distortion_block distort];
  53.     end
  54.     [distortion_min,ind]=min(distortion_block);
  55.     newdistortion=newdistortion+distortion_min;
  56.     index(i)=ind;
  57.   end
  58.   for l=1:codebook_size;
  59.     partition=(index==l);
  60.     if sum(partition)>0
  61.       updated_codebook(l,:)=partition*training_matrix/sum(partition);
  62.     end
  63.   end
  64.   newdistortion=newdistortion/m;
  65. end
  66. codebook=updated_codebook;
  67. distortion=newdistortion/dimension;