Change sequence of consecutive trues to falses, in logical array

조회 수: 7 (최근 30일)
Enrico Gambini
Enrico Gambini 2022년 10월 13일
편집: Bruno Luong 2022년 10월 13일
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
Bruno Luong 2022년 10월 13일
편집: Bruno Luong 2022년 10월 13일
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

추가 답변 (1개)

Chunru
Chunru 2022년 10월 13일
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
Enrico Gambini
Enrico Gambini 2022년 10월 13일
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by