Run Length Coding Matlab

1.5k views Asked by At

I am doing Run Length Coding in Matlab and so far I have implemented the zigzag algorithm and got an array RunLengthCoding:

RunLengthCoding = 
(32, 6, -1, -1, 0, -1, 0, 0, 0, -1, 0, 0, 1, 0, 0,..., 0)

Now I need to run length code this such that I get:

(0,6) (0,-1) (0,-1) (1,-1) (3,-1) (2,1) (0,0)

This is (length,value), for example (0,6) because there is no 0 and we are at value 6, then when we meet the first 0 we get (1,-1) since there is one 0 and the value after it is -1.

My attempt:

RunLengthCoding(1)=[]; %to remove first DC component
relMat = [];
N = 0;
for i = 1:length(RunLengthCoding)-1
     if RunLengthCoding(i)==0;
          if RunLengthCoding(i)==RunLengthCoding(i+1)
               N = N + 1;
          else
              valuecode = RunLengthCoding(i);
              lengthcode =  N;
              relMat = [relMat;  lengthcode valuecode];
              N = 1;
          end
        else
           relMat=[relMat; 0 RunLength(i)];  
    end

I know that this does not run! But that is what I have managed so far

2

There are 2 answers

14
Wouter Kuijsters On BEST ANSWER

This should do the trick:

RunLengthCoding = [77   -6  -11 -18 -6  -6  2   -1  4   -1  -1  6   3   1   -1  0   0   0   2   1   2   -1  -1  0   -1  1   0   0   0   0   0   0   -1  0   0   1   0   0   0   0   0   0   0 0 0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0];

RunLengthCoding(1)=[]; %to remove first DC component
relMat = [];

i = 0;
while i < length(RunLengthCoding)
    i=i+1;
    N = 0;
    while (RunLengthCoding(i)==0 && i < length(RunLengthCoding)) % keep going as long as we encounter zeros
        N=N+1;
        i=i+1;
    end
    relMat = [relMat N RunLengthCoding(i)]; % output the number of zeros we have encountered and the next value
end

if relMat(end)==0
    relMat(end-1)=0;
end
1
Bentoy13 On

Instead of doing such a complex loop, you can do the whole thing without any loop, in the following manner:

% RunLengthCoding is the input row vector
rlc_m = (RunLengthCoding~=0);
relmat = [diff(find(rlc_m))-1 ; RunLengthCoding([false,rlc_m(2:end)])];

I've put the output in two rows, but you can get a single row vector with relmat(:).'. I think it's an easier way to get the rlc.

Explanation: First I create the mask of all non-zero values, stored into rlc_m. Then the trick is the following: the non-zero values (2nd row) is the elements of the input where I mask the very first one. To grab the number of 0 between two numbers, I compute the difference of indexes of non-zeros elements in the input array, minus 1 to count the number of elements strictly between two indexes.