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

One way to find the longest sequence of the same value in an array and report the value is to use a while loop along with the max function. Here's an example code:

main.m
% Input array
A = [1 1 1 2 2 3 3 3 3 4 5 5 5];

% Initialize variables
max_value = A(1);   % maximum sequence value
max_count = 1;      % maximum sequence count
count = 1;          % current sequence count

% Traverse the array
i = 2;  % start from the second element
while i <= length(A)
    if A(i) == A(i-1)  % current element is same as previous element
        count = count + 1;
    else  % current element is different from previous element
        if count > max_count
            max_count = count;
            max_value = A(i-1);
        end
        count = 1;  % start a new sequence
    end
    i = i + 1;
end

% Check if the last sequence is the longest
if count > max_count
    max_count = count;
    max_value = A(end);
end

% Display the maximum sequence value and count
fprintf('The longest sequence of the same value is %d with count %d\n', max_value, max_count);
882 chars
32 lines

In this code, we initialize three variables: max_value, max_count, and count. We then traverse the array using a while loop, and count the length of each sequence of the same value. When we encounter a different value, we compare the current sequence count with the previous maximum count, and update the maximum count and value if the current sequence is longer. Finally, we display the maximum sequence value and count using the fprintf function.

For the input array [1 1 1 2 2 3 3 3 3 4 5 5 5], the output would be:

main.m
The longest sequence of the same value is 3 with count 4
57 chars
2 lines

gistlibby LogSnag