Advertisement
Guest User

Untitled

a guest
Nov 15th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 2.41 KB | None | 0 0
  1. clear all
  2.  
  3. % str = input('Введите фразу: ','s'); %вводим фразу
  4. text =
  5.  
  6. dl=length(text)%находим длину фразы
  7. ch = unique(text); %находим уникальные символы
  8. len=length(ch);
  9.  
  10. S=[];
  11. P=[];
  12.  
  13. for i = 1:length(ch) %берем i от 1 до количество алфавита
  14. k=length(findstr(text,ch(i)));%ищем длину каждого уникального символа
  15. p(i)=k/dl;%вероятность
  16. end    
  17. [p index]=sort(p);
  18.  
  19. ord_ch=ch(index);
  20.  
  21. codewords = huffmancode(p);
  22.  
  23. huffman='';
  24. for i=1:length(text)
  25.     for j=1:len
  26.         if text(i)==ord_ch(j)
  27.             huffman=strcat(huffman,codewords(j))
  28.         end
  29.     end
  30. end
  31. disp('Код Хаффмана')
  32. disp(huffman)
  33.  
  34.  
  35. function codewords = huffmancode(ver)
  36.  
  37.     dlina=length(ver); %длина массива индексов вероятности
  38.     codewords=cell(1,dlina); %это горизонтальный массив ячеек
  39.     symbols={}; %для индексов символов
  40.    
  41.     for i=1:dlina
  42.         symbols{i}=[i]; %в массив ячеек записываем индексы символов
  43.     end
  44.    
  45.     while (dlina > 1)
  46.         [~,minindex]=min(ver)
  47.         if minindex == 1 % С первым числом сравнение невозможно, это позволяет избавится
  48.         elseif minindex == dlina | round(ver(minindex - 1), 5) == round(ver(minindex + 1), 5)
  49.             minindex = minindex - 1;
  50.         end
  51.        
  52.         %сумма вероятностей и индексов
  53.         sum_ver = ver(minindex)+ver(minindex + 1);
  54.         sum_symbol = [symbols{minindex} symbols{minindex + 1}]
  55.        
  56.         %Добавляем нужные символы в таблицу кодовых символов
  57.         for i=1:length(symbols{minindex})
  58.             codewords{1, symbols{minindex}(i)}=strcat('0', codewords{1, symbols{minindex}(i)})
  59.         end
  60.         for i=1:length(symbols{minindex + 1})
  61.             codewords{1,symbols{minindex + 1}(i)}=strcat('1', codewords{1,symbols{minindex + 1}(i)})
  62.         end
  63.        
  64.         %вносим изменения
  65.         ver(minindex) = sum_ver;
  66.         symbols{minindex} = sum_symbol;
  67.        
  68.         %удаляем лишний элемент массива
  69.         ver(minindex + 1) = []
  70.         symbols(minindex + 1) = []
  71.     end
  72. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement