使用 matlab 查找大小为 1xn 的随机数组中最长的连续数字序列的大小



我想使用 Matlab 在大小为 1xn 的随机数组中找到最长的连续数字序列的大小。我知道有两种方法可以做到这一点:1) 使用循环和 2) 使用 Matlab 函数,例如 find,但我不确定如何在不使用两者的情况下做到这一点?

例如 [1 2 3 5 8 9 10 11 12 13 14 17]

其中最长的序列是 10 11 12 13 14,大小为 5。

我试过这个,但它不起作用:

function [start, finish] = longest(sequence)
x = diff(t)==1;
f = find([false,x]~=[x,false]);
g = find(f(2:2:end)-f(1:2:end-1)>=N,1,'first');

你的变量不匹配,但假设all(t == sequence)你走在正确的轨道上。您希望通过执行第二次diff来区分每次运行的开始和结束。

% Mark all sequences
x = diff(sequence) == 1;
% Take the second derivative to find the edges
xx = diff([false, x, false]);
% This gives matched pairs of indexes for each block
initial = find(xx == 1);
final = find(xx == -1);
% Get the block length
blockLength = final - initial;
% Get the max length
[~, idx] = max(blockLength);
% Return the indices
start = initial(idx);
finish = final(idx);

您的测试结果给出了start = 5finish = 11。如果还想返回块长度,请将~替换为变量名

最新更新