Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- clear all
- % str = input('Введите фразу: ','s'); %вводим фразу
- text =
- dl=length(text)%находим длину фразы
- ch = unique(text); %находим уникальные символы
- len=length(ch);
- S=[];
- P=[];
- for i = 1:length(ch) %берем i от 1 до количество алфавита
- k=length(findstr(text,ch(i)));%ищем длину каждого уникального символа
- p(i)=k/dl;%вероятность
- end
- [p index]=sort(p);
- ord_ch=ch(index);
- codewords = huffmancode(p);
- huffman='';
- for i=1:length(text)
- for j=1:len
- if text(i)==ord_ch(j)
- huffman=strcat(huffman,codewords(j))
- end
- end
- end
- disp('Код Хаффмана')
- disp(huffman)
- function codewords = huffmancode(ver)
- dlina=length(ver); %длина массива индексов вероятности
- codewords=cell(1,dlina); %это горизонтальный массив ячеек
- symbols={}; %для индексов символов
- for i=1:dlina
- symbols{i}=[i]; %в массив ячеек записываем индексы символов
- end
- while (dlina > 1)
- [~,minindex]=min(ver)
- if minindex == 1 % С первым числом сравнение невозможно, это позволяет избавится
- elseif minindex == dlina | round(ver(minindex - 1), 5) == round(ver(minindex + 1), 5)
- minindex = minindex - 1;
- end
- %сумма вероятностей и индексов
- sum_ver = ver(minindex)+ver(minindex + 1);
- sum_symbol = [symbols{minindex} symbols{minindex + 1}]
- %Добавляем нужные символы в таблицу кодовых символов
- for i=1:length(symbols{minindex})
- codewords{1, symbols{minindex}(i)}=strcat('0', codewords{1, symbols{minindex}(i)})
- end
- for i=1:length(symbols{minindex + 1})
- codewords{1,symbols{minindex + 1}(i)}=strcat('1', codewords{1,symbols{minindex + 1}(i)})
- end
- %вносим изменения
- ver(minindex) = sum_ver;
- symbols{minindex} = sum_symbol;
- %удаляем лишний элемент массива
- ver(minindex + 1) = []
- symbols(minindex + 1) = []
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement