How to search the continuous values with maximal size in a vector ?

How to search continuous values in a vector,meanwhile,the size of the continuous values is the largest? For example,
a=[1 2 3 4 5 6 7 11 13 14 15 18 19]
Here the answer should be
ans=[1 2 3 4 5 6 7]
Help me to find the answer for vector of size n. I want to use this to detect a portion which is linear in a curve. Is there some function in MATLAB which could do this work? Thanks.

 采纳的回答

You can go for a solution around the following:
boundary = find([true, abs(diff(a))~=1, true]) ;
[blockSize, boundaryStart] = max(diff(boundary)) ;
With this and a defined by
>> a= [1 2 3 0 5 6 7 11 13 14 15 16 18 19] ;
you get:
>> boundary % Starting ID of blocks of contiguous integers.
boundary =
1 4 5 8 9 13 15
>> blockSize % Size of the first largest blocks.
blockSize =
4
>> boundaryStart % Starting ID of first largest block.
boundaryStart =
5
which you can use e.g. as follows:
>> blockRange = boundary(boundaryStart) + (0:blockSize-1) ;
>> a(blockRange)
ans =
13 14 15 16
Note that this method can be easily updated so you get all blocks that have the largest size.. it would be something like (not tested):
bDiff = diff(boundary) ;
boundaryStarts = find(bDiff==max(bDiff)) ;
and then you can iterate through elements of boundaryStarts to get all relevant blocks.

更多回答(1 个)

I wrote this function:
function y=continuous(a)
n=length(a);
for i=1:n-1
if diff(a(i:i+1))==1
z(i)=a(i);
z(i+1)=a(i+1);
end
end
y=z(z~=0);
In this way, if a is [1 2 3 4 5 6 7 11 13 14 15 18 19], the result y will be only the continuous part of a, [1 2 3 4 5 6 7 13 14 15 18 19].

1 个评论

Hi,thanks,for the continuous set you have got, I have added some line, so that the size of the continuous values is the largest.it goes just like this:
function y=continuous(a) n=length(a); for i=1:n-1 if diff(a(i:i+1))==1 z(i) = a(i); z(i+1) = a(i+1); end end z = z(z~=0); ind = find(diff(z)>1); ind = [0 ind length(z)]; s = cell(1,length(ind)-1); for i=1:length(ind)-1 s{i}= z(ind(i)+1:ind(i+1)); len(i)=length(s{i}); end y = s{find(max(len))};
In this way, if a is [1 2 3 4 5 6 7 11 13 14 15 18 19], the result y will be[1 2 3 4 5 6 7].
But regretful,I feel the method is not so well--kind of complicated for such a simple problem. Any good suggestions?

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Computer Vision Toolbox 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by