Arrays 用matlab求1xn随机数组中最长连续数序列的大小

Arrays 用matlab求1xn随机数组中最长连续数序列的大小,arrays,matlab,sequence,Arrays,Matlab,Sequence,我想使用Matlab在一个1xn大小的随机数组中找到最长的连续数字序列的大小。我知道有两种方法可以做到这一点:1)使用循环和2)使用Matlab函数,例如find,但我不确定在不同时使用这两种函数的情况下如何做到这一点 例如,[1 2 3 5 8 9 10 11 12 13 14] 其中最长的序列是101121314,大小为5 我试过这个,但不起作用: function [start, finish] = longest(sequence) x = diff(t)==1; f = find(

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

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

其中最长的序列是101121314,大小为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=5
finish=11
。如果您还想返回块长度,请将
~
替换为您的变量名

这是一个很大的帮助,请设法解决它,谢谢。我的朋友提到,在没有diff和max内置函数的情况下,只使用循环(即)是可能的,但我不知道从哪里开始?我在猜测写一个循环以保持计数并保存每个序列的长度,然后如果发现更长的序列,则替换该长度。你会怎么写呢?考虑到MATLAB通常是针对矢量化进行优化的,答案是我不会。我认为没有理由一次只检查一个向量元素,因为你可以让MATLAB一下子完成这一切。