Extract vector parts around index under boolean conditions

9 Ansichten (letzte 30 Tage)
moar0504
moar0504 am 12 Jun. 2019
Kommentiert: Guillaume am 13 Jun. 2019
Hello everybody,
I am trying to extract parts of a signal that meet a certain condition (boolean true) and save them into individual vectors.
Lets say i have a testvector:
testvector = [0 0 1 0 0 0 1 1 1 1 1 1 1 1 0 0 0 1 0 0 1];
Iterating through the signal, if the index is true, I want to check if:
  • i-3 positions are 0 (condition1)
  • i+5 positions are 1 (condition2)
If both conditions are true, I would like to extract this part of the signal, like mentioned earlier.
Concerning my testvector, due to my conditions there is supposed to be exactly one part to be extracted:
testvector(4:12)
Until now, I've tried the following without success:
values=[];
for i=4:numel(testvector)
if testvector(i)==1
buff1 = i-3;
buff2 = i+5;
for k=buff1:1:(i-1)
values = [values, testvector(k)];
if any(values)
values(end) = [];
break
elseif length(values)>3
break
end
end
for k=i:1:buff2
values = [values, testvektor(k)];
if any(values)
break
elseif buff2 > numel(testvektor)
break
elseif (length(values)>10)
continue
end
end
new = [new, testvektor(i)]
end
end
So far, I have no idea how to automatically construct a new vector each time the conditions are met and a part of the signal is extracted.
Thank you in advance, every help is highly appreciated!

Akzeptierte Antwort

Guillaume
Guillaume am 12 Jun. 2019
One way:
testvector = repmat([0 0 1 0 0 0 1 1 1 1 1 1 1 1 0 0 0 1 0 0 1], 1, 3); %replicate your demo vector so that there is more than one segment to extract
before = movsum(testvector(1:end-5), [3 0], 'Endpoints', 'discard'); %sum of 3 elements before + current element. Will be 1 if a 1 is preceded by three 0s
after = movsum(testvector(4:end), [0 5], 'Endpoints', 'discard'); %sum of 5 elements after + current element. Will be 6 if a 1 is followed by five 1s
indices = find(before == 1 & after == 6 & testvector(4:end-5) == 1); %construct a row vector of indices where the condition is true
segments = testvector(indices + (0:9)') %extract all segments as column vectors
  2 Kommentare
moar0504
moar0504 am 13 Jun. 2019
Sir, you are a genius!
Thank you very much for providing a quite simple as also logical solution!
Guillaume
Guillaume am 13 Jun. 2019
On thing that puzzles me about your requirements is that the segments to be extracted are always going to be [0 0 0 1 1 1 1 1 1], so why bother with the extraction? In any case, my answer gives you the starting locations of the segments (in indices) which is probably more useful.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu ROS Toolbox Supported Hardware finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by