-
3 Comments
@Piero Cimule
Could you please comment on this method? It is very unlikely for me as a beginner in Matlab to have such a concise code. You are more than welcome to elaborate here or via my e-mail address zasevzasev42@gmail.com
Really succinct code. One of the best I saw so far in the contest. @Piero Cimule
@Jovan Krunic:
%
% find(vertcat(1,diff(a(:)),1))
% val=a(ans(diff(ans)==max(diff(ans))))
%
% the approach is:
% find the differences between the elements of the vector
% consecutive zero's mean there is a run of the same values
% get the indices of none zero elements of this vector
% get the differences of these indices (which are a measure for the length the run of consecutive zero's, the 'gap' resulting from removing the zeros)
% note that to make this work for vectors that start or end with the longest run we add a 1 to the beginning and the end of the first difference vector
% get the max value from this last result which is the max sequence length
% get the indices of these max values, that is, the first indices of the runs that have this max length
% note that this last result is always a column vector
% get the values of the first elements of the runs with max length from the original vector
% note that if the original vector was a row vector, the result will be a row vector and when it was a column vector the result is a column vector,
% as required in the problem description
function val=longrun(a)
val = [];
if length(a) > 0
% a(:) will convert a to a column vector
a_as_column_vector = a(:);
% differences between elements of a
diff_a = diff(a_as_column_vector);
% differences between elements of a enclosed in ones (to make sure first and last element are non zero)
vertcat_1_diff_a_1 = vertcat(1, diff_a, 1);
% non zero elements of vertcat_1_diff_a_1
find_vertcat_1_diff_a_1 = find(vertcat_1_diff_a_1);
% the difference between the non zero indices is equal to the length of the run of consecutive numbers
lengts_of_runs_of_consecutive_numbers = diff(find_vertcat_1_diff_a_1);
% set the elements that have the max length to one and the others to 0 - note that shift of indices as a result of diff is compensated by adding 1 at the front of the vector
indices_of_elements_that_have_max_length_run = lengts_of_runs_of_consecutive_numbers == max(lengts_of_runs_of_consecutive_numbers);
indices_of_first_elements_of_longest_run_of_consecutive_numbers = find_vertcat_1_diff_a_1(indices_of_elements_that_have_max_length_run);
values_of_first_elements_of_longest_run_of_consecutive_numbers = a(indices_of_first_elements_of_longest_run_of_consecutive_numbers);
val = values_of_first_elements_of_longest_run_of_consecutive_numbers;
end
end
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!