Change sequence of consecutive trues to falses, in logical array

4 次查看(过去 30 天)
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