为了巧妙地使用线性索引accumarray,我有时觉得需要根据游程编码生成序列.由于没有内置函数,我要求最有效的方法来解码在RLE中编码的序列.
为了使这个公平比较,我想为该功能设置一些规范:
values指定了相同长度的可选第二个参数,则输出应该根据这些值,否则只是值1:length(runLengths).runLengthsvalues 是一个单元阵列.runLengths 简而言之:该函数应该等效于以下代码:
function V = runLengthDecode(runLengths, values)
[~,V] = histc(1:sum(runLengths), cumsum([1,runLengths(:).']));
if nargin>1
V = reshape(values(V), 1, []);
end
V = shiftdim(V, ~isrow(runLengths));
end
Run Code Online (Sandbox Code Playgroud)
以下是一些测试用例
runLengthDecode([0,1,0,2])
runLengthDecode([0,1,0,4], [1,2,4,5].')
runLengthDecode([0,1,0,2].', [10,20,30,40])
runLengthDecode([0,3,1,0], {'a','b',1,2})
Run Code Online (Sandbox Code Playgroud)
和他们的输出:
>> runLengthDecode([0,1,0,2])
ans =
2 4 4
>> runLengthDecode([0,1,0,4], [1,2,4,5].')
ans =
2 5 5 5 5
>> runLengthDecode([0,1,0,2].', [10,20,30,40])
ans =
20
40
40
>> runLengthDecode([0,3,1,0],{'a','b',1,2})
ans …Run Code Online (Sandbox Code Playgroud)