Very low readability, and there is actually no need to write in R language, just a picture of fun.
p=c(0.4,0.2,0.2,0.1,0.1)###Input a probability vector of form c(0.4, 0.2, 0.2, 0.1, 0.1), that is, the probability of occurrence of each message to be encodedp1=p###Save the probability vector and finally calculate the encoding efficiency.mazijuzhen=matrix(,nrow=length(p),ncol=length(p)-1)###Coding word matrix: the encoded codeword of the message to be encoded corresponding to the i-th component of the vector p in the i-th linegroup=matrix(c(1:length(p),rep(NA,length(p)*(length(p)-1))),nrow=length(p),ncol=length(p))###Initial grouping: Each row represents a group, and all components of each row vector represent all elements of this group. At the beginning, there are as many groups as there are messages to be encoded. Each group has only one message to be encoded. The integer i represents the message to be encoded corresponding to the i-th component of vector p.i=1###Start codingfor(i in 1:(length(p)-1)) { orderp=order(p,decreasing = FALSE)The components of ###orderp are: the subscript of the minimum component of p and the subscript of the second small component of p. . . mazijuzhen[group[orderp[1],],i]=0###Class the two message groups with the least probability 0 and 1 mazijuzhen[group[orderp[2],],i]=1 group[min(c(orderp[1],orderp[2])),]=c((group[min(c(orderp[1],orderp[2])),]),(group[max(c(orderp[1],orderp[2])),]),rep(NA,length(p)-length(c((group[min(c(orderp[1],orderp[2])),]),(group[max(c(orderp[1],orderp[2])),])))))###Split the two message groups in this iteration with larger group numbers into the groups with smaller group numbers. group[max(c(orderp[1],orderp[2])),]=NA###Delete groups with larger group numbers p[min(c(orderp[1],orderp[2]))]=p[orderp[1]]+p[orderp[2]]### Calculate the probability of occurrence of new message groups obtained in this iteration p[max(c(orderp[1],orderp[2]))]=NA### Since a group with a larger group number is deleted, the corresponding probability of deleting it is correspondingly deleted. print("Current iterations")###Summary of the results of this iteration print(i) print("Probability vector") print(p) print("Group matrix") print(group) print("Coding word matrix") print(mazijuzhen) } i=1### Features encoded by Hoffman, invert all encodings to get the final encodingfor (i in 1:length(p)) { mazijuzhen[i,]=rev(mazijuzhen[i,]) } i=1###Build code length vectormachang=c() for (i in 1:length(p)) { machang=c(machang,length((mazijuzhen[i,]))) } xiaolv=-p1%*%log(p1,2)/mean(machang)###Computation and coding efficiencyprint("The final codeword matrix and encoding efficiency") mazijuzhen xiaolv
This is the end of this article about the example code of Hoffman encoding using R language. For more related R languages, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!