mathshelp101
mathshelp101

Reputation: 21

Find the first longest consecutive set of 1's in a Vector in matlab

I have the following vector in matlab:

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

I want to be able to find the longest consecutive set of 1's (so in this case it would be 3) and then print the index where this set arises (3 and 5).

In this scenario 1 1 1 shows up twice, I would like it to make sure it prints the index of where the first set is.

What coding can I use for this - but without using any in-built matlab functions, only for loops.

Upvotes: 0

Views: 198

Answers (2)

Irreducible
Irreducible

Reputation: 899

Here an implementation without matlab functions:

%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

Output

max_length =

 3


max_start_idx =

 3

max_end_idx =

 5

Upvotes: 2

Adiel
Adiel

Reputation: 3071

Here is a solution without built-in functions. I understand that you want the indices of the begin and end of the first longest sequence.

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

Upvotes: 1

Related Questions