Advertisement
makispaiktis

Quantization of a signal

May 25th, 2022 (edited)
1,051
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 0.95 KB | None | 0 0
  1. clc
  2. clear all
  3.  
  4. % Data
  5. start = 0;
  6. finish = 4*pi;
  7. x = linspace(start, finish, 100);
  8. y = sin(x);
  9. MIN = min(y);
  10. MAX = max(y);
  11. % Levels
  12. R = 4;
  13. num_levels = 2 ^ R;
  14. differ = (MAX - MIN) / num_levels;
  15. levels = zeros(1, num_levels);
  16. for i = 1 : num_levels
  17.     levels(i) = MIN + (2*i - 1) * differ / 2;
  18. end
  19.  
  20. % Searching 'y' to snap the values
  21. multiplier = 3;                     % Must be an integer!
  22. LEN = round(multiplier * length(y));
  23. q = zeros(1, LEN);
  24. t = zeros(1, LEN);
  25.  
  26. for i = 1 : LEN
  27.     pos = round(i / multiplier);
  28.     if pos == 0
  29.         value = y(1);
  30.         t(i) = x(1);
  31.     else
  32.         value = y(pos);
  33.         t(i) = x(pos);
  34.     end
  35.     index = -1;
  36.     d = MAX - MIN;
  37.     for j = 1 : length(levels)
  38.         level = levels(j);
  39.         if abs(level-value) <= d
  40.             d = abs(level-value);
  41.             index = j;
  42.         end
  43.     end
  44.     q(i) = levels(index);
  45. end
  46.  
  47.  
  48. % PLOTS
  49. levels
  50. plot(x, y);
  51. hold on
  52. plot(t, q);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement