Change sequence of consecutive trues to falses, in logical array

4 Ansichten (letzte 30 Tage)
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!

Akzeptierte Antwort

Bruno Luong
Bruno Luong am 13 Okt. 2022
Bearbeitet: Bruno Luong am 13 Okt. 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

Weitere Antworten (1)

Chunru
Chunru am 13 Okt. 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
  1 Kommentar
Enrico Gambini
Enrico Gambini am 13 Okt. 2022
Thank you for the answer!
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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by