找到连续数字的中间点

时间:2014-10-15 03:48:57

标签: matlab

我说我有

A=[1 3 4 5 6 7 9 12 15 16 17 18 20 23 24 25 26];

我感兴趣的是如何使用Matlab找到连续数字之间的中间值。

例如,第一组连续数字是

B=[3 4 5 6 7];

所以答案应该是5。第二组连续数字(即[15 16 17 18])应该给16等......

最后,我的最终答案是

[5 16 24]

3 个答案:

答案 0 :(得分:3)

这是一种矢量化方法:

d = [diff(A) == 1, 0];
subs = cumsum([diff(d) == 1, 0]).*(d | [0, diff(d) == -1]) + 1
temp = accumarray(subs', A', [], @median)
final = floor(temp(2:end))

答案 1 :(得分:2)

以下是一些示例代码,可以满足您的需求。我会让你玩不同的输出来看他们到底做了什么,虽然我写了一些评论:

clear
clc

A=[1 3 4 5 6 7 9 12 15 16 17 18 20 23 24 25 26]

a=diff(A); %// Check the diff array to identify occurences different than 1.

b=find([a inf]>1);
NumElements=diff([0 b]); %//Number of elements in the sequence

LengthConsec = NumElements((NumElements~=1)) %// Get sequences with >1 values
EndConsec = b(NumElements~=1) %// Check end values to deduce starting values
StartConsec = EndConsec-LengthConsec+1;

%// Initialize a cell array containing the sequences (can have ifferent
%lengths, i.e. an array is not recommended) and an array containing the
%median values.
ConsecCell = cell(1,numel(LengthConsec));
MedianValue = zeros(1,numel(LengthConsec));

for k = 1:numel(LengthConsec)

    ConsecCell{1,k} = A(StartConsec(k):1:EndConsec(k));
    MedianValue(k) = floor(median(ConsecCell{1,k}));
end

%//Display the result
MedianValue

给出以下内容:

MedianValue =

     5    16    24

答案 2 :(得分:1)

基于{p> diff + strfind的方法 -

loc_consec_nums = diff(A)==1 %// locations of consecutive (cons.) numbers
starts = strfind([0 loc_consec_nums],[0 1]) %// start indices of cons. numbers
ends = strfind([loc_consec_nums 0],[1 0]) %// end indices of cons. numbers
out = A(ceil(sum([starts ; ends],1)./2))%// median of each group of starts and ends
              %// and finally index into A with them for the desired output
相关问题