Matlab中的运行长度编码

use*_*895 4 matlab run-length-encoding

我对MatLab很新,我有运行长度编码代码,但似乎不起作用,你能帮助我吗?

我有这个输入:

ChainCode  = 11012321170701000700000700766666666666665555555544443344444333221322222322 
Run Code Online (Sandbox Code Playgroud)

我想把它变成RLE输出:

(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) 
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

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
Run Code Online (Sandbox Code Playgroud)

但这不起作用,我仍然对如何打印输出这样做感到困惑.

我希望你能帮助我.谢谢.

Moh*_*nia 12

这是一个没有循环,cellfun或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])];
Run Code Online (Sandbox Code Playgroud)