# Change sequence of consecutive trues to falses, in logical array

1 view (last 30 days)
Enrico Gambini on 13 Oct 2022
Edited: Bruno Luong on 13 Oct 2022
Hello guys!
I would like to find a fast procedure to change from true to false the consecutive trues in a logical array excluding only the first and the last true in the sequence.
For instance:
x=[true;false;false;true;true;true;true;true];
Desired output array should be:
output=[true;false;false;true;false;false;false;true];
Hope the question is clear.
Thank you!

Bruno Luong on 13 Oct 2022
Edited: Bruno Luong on 13 Oct 2022
x=[true;false;false;true;true;true;true;true;false;true]'
x = 1×10 logical array
1 0 0 1 1 1 1 1 0 1
x & ~([false,x(1:end-1)]&[x(2:end),false])
ans = 1×10 logical array
1 0 0 1 0 0 0 1 0 1

Chunru on 13 Oct 2022
x=[true;false;false;true;true;true;true;true]'
x = 1×8 logical array
1 0 0 1 1 1 1 1
output = x;
dx = diff(x(1:end-1))
dx = 1×6
-1 0 1 0 0 0
output1 = output(2:end-1);
output1(output1 & (dx==0)) = false;
% Desired output array should be:
output(2:end-1) = output1;
output
output = 1×8 logical array
1 0 0 1 0 0 0 1
% Desired
[true;false;false;true;false;false;false;true]'
ans = 1×8 logical array
1 0 0 1 0 0 0 1
Enrico Gambini on 13 Oct 2022
It does not work if a false is present after the last true of each sequence, for instance, if I had a vector like this:
x=[true;false;false;true;true;true;true;true;false;true]'
x = 1×10 logical array
1 0 0 1 1 1 1 1 0 1
output = x;
dx = diff(x(1:end-1))
dx = 1×8
-1 0 1 0 0 0 0 -1
output1 = output(2:end-1);
output1(output1 & (dx==0)) = false;
% Desired output array should be:
output(2:end-1) = output1;
output
output = 1×10 logical array
1 0 0 1 0 0 0 0 0 1
%Desired should be
[1,0,0,1,0,0,0,1,0,1]
ans = 1×10
1 0 0 1 0 0 0 1 0 1
I really need to automate this procedure and be sure it is robust, since I am dealing with very large array.
Thank you

### Categories

Find more on Matrices and Arrays in Help Center and File Exchange

R2021a

### Community Treasure Hunt

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

Start Hunting!