How can I delete a row based on the value of the previous row?
조회 수: 9 (최근 30일)
I have a file containing one column and a large number of rows. I want to delete any row whose value is less than 2 greater than the previous row (ie if row 1 is 10, and row 2 is 11, then delete row 2. If row 1 is 10, and row 2 is 12.1, then don't delete it). How can I do this? I know how to delete specificied rows with something like
rowstodelete = xxxxxx
A(rowstodelete,:) = [ ];
But I don't know how to figure out which rows need to be deleted (ie what do I need to put in for xxxxx.) I was thinking maybe using logical indexing or if-else statments, but not really sure how. Open to other options too! Thanks in advance!
Walter Roberson 2022년 7월 31일
편집: Walter Roberson 님. 2022년 7월 31일
Not a full algorithm, but something to think about
data = randi(99, 1, 20) %row vector
G = tril(data.'-2 >= data)
pos = sum(cumprod(~G,1),1)+1
find the first 1 in the first column of G; it is at row 2. Entry 2 is the first entry in data that is at least 2 greater than entry 1. Cross check: 62 >= 19+2. Let C = 2 (column 2). pos(1) = 2 -- the required value of the first 1
Look in column C (#2) for the first 1; it is at entry 4. Entry 4 is the first entry in data that is at least 2 greater than entry 2. Cross-check: 78 >= 62+2. Let C = 4 (column 4). pos(2) = 4 -- the required value of the first 1
Look in column C (#4) for the first 1; it is at entry 8. Entry 8 is the first entry in data that is at least 2 greater than entry 4. Cross-check: 80 >= 78+2. Let C = 8 (column 8). pos(4) = 8 -- the required value of the first 1
Look in column C (#8) for the first 1. pos(8) = 9, entry 9 is the first entry, 95 >= 80+2
and so on. The G matrix is the details, the pos vector is the condensed information, the position you need. So you can just read the positions out of pos. pos(1) gives the next index to look at in pos, pos() at that gives the next index, and so on.
When you get an index that is 1 greater than the number of elements in data then you have reached the end, there are no more positions that satisfy the condition.