Run Length Encoding in Matlab

user1146895 picture user1146895 · Aug 21, 2012 · Viewed 9.9k times · Source

I'm very new with MatLab, I have Run Length Encoding code but it seems to not work, can you help me?

I have this input :

ChainCode  = 11012321170701000700000700766666666666665555555544443344444333221322222322 

and I want make it into RLE output :

(1,2), (0,1), (1,1), (2,1), (3,1), (2,1), (1,2), (7,1), (0,1), (7,1), (0,1), 
(1,1), (0,3), (7,1), (0,5), (7,1), (0,2), (7,1), (6,13), (5,8), (4,4), (3,2), 
(4,5), (3,3), (2,2), (1,1), (3,1), (2,5), (3,1), (2,2) 

This is my code :

lengthcode = 1;
N = 1;

for i = 2:length(ChainCode)

    if x(i)==x(i-1)
        N = N + 1; 
        valuecode(N)  = x(i);
        lengthcode(N) = lengthcode(N) + 1;
    else 
        N = 1;
        lengthcode = 1;
    end

    i = i + 1;

end

But this is not working, and I am still confused about how can I print the output like that.

I hope you can help me. Thank you.

Answer

Mohsen Nosratinia picture Mohsen Nosratinia · Aug 28, 2013

Here is a compact solution without loop, cellfun or arrayfun:

chainCode = '11012321170701000700000700766666666666665555555544443344444333221322222322';
numCode = chainCode - '0'; % turn to numerical array

J=find(diff([numCode(1)-1, numCode]));
relMat=[numCode(J); diff([J, numel(numCode)+1])];