【问题标题】:Find the first longest consecutive set of 1's in a Vector in matlab在matlab中的向量中找到第一个最长的连续1集
【发布时间】:2017-10-16 21:07:36
【问题描述】:

我在matlab中有以下向量:

[1 0 1 1 1 0 0 1 1 0 1 1 1] 

我希望能够找到最长的连续 1 集(因此在本例中为 3),然后打印该集出现的索引(35)。

在这种情况下1 1 1 出现两次,我希望它确保它打印出第一组的索引。

我可以为此使用什么编码 - 但不使用任何内置的 matlab 函数,仅用于循环。

【问题讨论】:

标签: matlab matrix count


【解决方案1】:

这里是一个没有matlab函数的实现:

%Example Vector
V=[1 0 1 1 1 0 0 1 1 1  0 1 1 0 1 1 1 0] ;

%calculate the diff of input
diff_V=V(2:end)-V(1:end-1);
N=length(diff_V);

% prepare start and end variables
start_idx=[]; end_idx=[];
%loop to find start and end
for kk=1:N

    if diff_V(kk)==1 %starts with plus
        start_idx=[start_idx kk+1];
    end

    if diff_V(kk)==-1 %ends with minus
        end_idx=[end_idx kk];
    end

end
% check if vector starts with one and adapt start_idx
if start_idx(1)>end_idx(1)
start_idx=[1 start_idx];
end

% check if vector ends with one and adapt end_idx
if start_idx(end)>end_idx(end)
end_idx=[end_idx length(V)];
end

%alloc output
max_length=0;
max_start_idx=0;
max_end_idx=0;
%search for start and length of longest epoch
for epoch=1:length(start_idx)
    epoch_length=end_idx(epoch)-start_idx(epoch)+1;
    if epoch_length> max_length
        max_length=epoch_length;
        max_start_idx=start_idx(epoch);
        max_end_idx=end_idx(epoch);
    end
end

输出

max_length =

 3


max_start_idx =

 3

max_end_idx =

 5

【讨论】:

    【解决方案2】:

    这是一个没有内置函数的解决方案。我知道您想要第一个最长序列的开头和结尾的索引。

    data=[1 0 1 1 1 0 0 1 1 0 1 1 1];
    
    x=[data 0];
    
    c=0;
    for k=1:length(x)
      if x(k)==1
        c=c+1;
      else
        ind(k)=c;
        c=0;
      end
    end
    
    a=ind(1);
    for k=2:length(ind)
       if ind(k)>a
           a=ind(k);
           b=k;
       end
    end
    
    Ones_start_ind=b-a
    Ones_end_ind=b-1
    
    % results:
    Ones_start_ind =
     3
    Ones_end_ind =
     5
    

    【讨论】:

    • max 是一个内置函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多