How to make my logical data homogene?
Show older comments
Hi all,
I have a vector logical data which varies between 0 and 1 in this way:
data = [0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0];
the number of repetition of zeros and ones are irregular as seen above. My problem is that in some points some ONES are dropped out like this:
data = [0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 1 1 1 1 1 0 1 1 0 0 0 0 0 0 1 1 1 1 0 1 1 1 0 0 0 0];
As you see elements number 15, 22 and 35 are exchanged from 1 to 0 in compared to the previous vector. I could fix it with a for loop asking to replace 0 to 1 every time there is a 0 between two 1s. But I was looking for some other way to avoid for loop.
I really appreciate any help.
Accepted Answer
More Answers (2)
Star Strider
on 6 Jan 2015
I would use the filter function to find them:
data1 = [0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0];
data2 = [0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 1 1 1 1 1 0 1 1 0 0 0 0 0 0 1 1 1 1 0 1 1 1 0 0 0 0];
difdata2 = diff([0 data2]);
data2flt = filter([1 -1], 2, difdata2);
data2z = find(data2flt == 1)-1;
where ‘data2z’ are the indices of the positions you want.
The code is relatively uncomplicated. The ‘difdata2’ assignment simply computes the differences between the elements, with the initial zero resulting in its length being the same as ‘data2’. The ‘data2flt’ assignment uses filter to detect the desired patterns. Because of the way filter operates, this is offset by the length of the filter - 1. The ‘data2z’ assignment returns these positions, correcting for the offset. So long as your data conform to the data you’ve posted, this code should work.
This also works (note the absence of the offset, although ‘difdata2’ is now one element shorter than ‘data2’):
difdata2 = diff(data2);
data2flt = filter([1 -1], 2, difdata2);
data2z = find(data2flt == 1);
Much depends on your data and how you want to process it.
Categories
Find more on MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!