Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Length Encoding in Matlab

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.

like image 965
user1146895 Avatar asked Dec 12 '22 23:12

user1146895


1 Answers

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])];
like image 91
Mohsen Nosratinia Avatar answered Dec 26 '22 12:12

Mohsen Nosratinia