find longest sequence of same values in array and report value in matlab

To find the longest sequence of the same values in an array in Matlab, you can use the diff function to compute the difference between consecutive elements of the array. Then you can use the find function to determine where the difference changes sign (from positive to negative or vice versa) and look at the differences between these indices to determine the lengths of the runs of consecutive elements with the same value. Finally, you can report the value of the longest run using indexing.

Here's an example implementation:

main.m
% Example array
arr = [1 2 2 2 3 3 4 5 5 5 5 5 6 6];

% Compute the differences
diffs = diff(arr);

% Find where the sign changes and add the endpoints of the array
run_ends = [0; find(diffs ~= 0); numel(arr)];

% Compute the lengths of the runs
run_lengths = diff(run_ends);

% Find the longest run and report the value
[max_length, max_idx] = max(run_lengths);
max_val = arr(run_ends(max_idx)+1);

fprintf('Longest run is %d with length %d\n', max_val, max_length)
467 chars
18 lines

This will output:

main.m
Longest run is 5 with length 5
31 chars
2 lines

indicating that the longest run of the same value in the array is 5, and it occurs five times in a row.

gistlibby LogSnag