File Exchange

image thumbnail

runindex

version 3.1.2 (2.55 KB) by Jos (10584)
linear indices for each run in a vector (run length encoding, and decoding)

3 Downloads

Updated 08 Feb 2019

View License

For a vector V, I = runindex(V) returns a vector I of the same size as
V with linear indices per run within V. Runs are contiguous sequences
of one value for one or more consecutive elements in V.

Example:
% create a vector with four runs: 3x20, 2x4, 4x55, 1x999
V = [20 20 20 4 4 55 55 55 55 999]
I = runindex(V)
% [ 1 2 3 1 2 1 2 3 4 1]

[I, RLE] = rundindex(V) also returns a run length encoding of V in
the N-by-3 array RLE. Each row is a run, with the value in the first
column, the start index in the second column, and the run length in
the third column. N is the number of runs.

V = [8 7 7 7 3 3 12 12 12 12]
[~, RLE] = runindex(V)
% RLE =
% 8 1 1
% 7 2 3
% 3 5 2
% 12 7 4

When given two input vectors U and C, V = runindex(U, C) decodes the
vectors U (values) and C (counts) into the vector V. V is the
concatenation of all values of U, where the k-th value U(k) is
repeated C(k) times. V is a sum(C)-by-1 column vector. When C(k) is 0,
U(k) is omitted from the vector.
[V, RLE] = runindex(U, C) returns the run-length encoding of V in RLE.

V = runindex([5 10 99], [2 1 3])
% V = [5 5 10 99 99 99]

Vin = [1 1 2 2 1 1 1]
[I, RLE] = runindex(Vin) % encoding
% I = [1 2 1 2 1 2 3]
Vout = runindex(RLE(:,1), RLE(:,3)) % decoding
% Vout equals Vin

V = runindex([0 1 0 2], [2 3 1 4])
% V = [0 0 1 1 1 0 2 2 2 2]) ;

See also cumsum, diff, find

Notes
- This function is related to run-length encoding:
https://en.wikipedia.org/wiki/Run-length_encoding

Cite As

Jos (10584) (2019). runindex (https://www.mathworks.com/matlabcentral/fileexchange/56131-runindex), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (2)

One of my favorite helper functions.

Tidy, well-written, excellent documentation, this code does exactly what it says on the box.

And it always reminds me of this rather enjoyable thread:
<https://www.mathworks.com/matlabcentral/answers/274911-do-you-have-a-suggestion-for-a-name-of-my-function>

Updates

3.1.2

fixed small mistake in the help

3.1.1

new image

3.1

new image

3.0.0.0

added decoding

MATLAB Release Compatibility
Created with R2017b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Acknowledgements

Inspired by: RunLength