Saturday, January 30, 2016

Runlength encoding in matlab

This post talks about Run Length Encoding in Matlab, the code of which I found in the book by David Salomon, the complete reference by springer.(The code as usual is a brilliant piece of work something i would never have achieved)

If you want to know the theory behind Run Length Encoding this post won't help you much but if you want its implementation i an going to give you MATLAB code with line by line explanation.

Here is the code:

%returns the run lengths of
% a martix of 0s and 1s
function R=runlengths(M)
[c,r]=size(M);
for i=1:c
    x(r*(i-1)+1:r*i)=M(i,:);    %flatten the matrix
    % ie store all rows in a single row matrix
end
N=r*c;
y=x(2:N);
u=x(1:N-1);
z=y+u;
j=find(z==1);
i1=[j N];
i2=[0 j];
R=i1-i2;

To test the code you need to assign a matrix M as follows
M=[0 0 0 1;1 1 1 0;1 1 1 0];
runlengths(M)          % this invokes the matlab function defined earlier
ans =
     3     4     1     3     1
Now the explanation part:
As evident in the comment part of the code in the function the first thing that is done is to flatten the matrix. Once the matrix is in row matrix form(ie x)
i)we store all elements of it starting from second element onwards in another matrix y
ii)we store all elements of it starting from first element except the last in matrix u
then we add the two matrices into z.
then find all positions of 1 in z
then create a matrix i1 with these positions and another number N denoting the end of the matrix
then we create a matrix i2 with zero as start value and these positions as other elements
finally we subtract i1 and i2 to get the result.
(A more detailed description will follow... I hope this is enough right now)