# Delete rows in loop For and using Delete

I want to delete several rows from file txt and I'm using this code

i = 24;
For[n = 0, n < 5500, n += 50, a = Delete[data, {{i - 1 + n}, {i + n}, {i + 1+ n}, {i + 2 + n}, {i + 3 + n}, {i + 4 + n}}]]


But when I do this I only get result which only delete lasts row so in this case delete only row from 5473 to 5478 and the others rows are the same.

• At each step in the loop,a gets a new value. Therefore, the final value of a will be Delete[data, {{24 - 1 + 5450}, {24 + 5450}, {24 + 1+ 5450}, {24 + 2 + 5450}, {24 + 3 + 5450}, {24 + 4 + 5450}}]. – Kiro Nov 18 '16 at 11:50

I will go ahead and also show you step by step how to do this without loops. You have data, and you want to delete the elements in specific positions and save the result in a. Let's see how it could go. First try

Range[-1, 4]
(*{-1, 0, 1, 2, 3, 4}*)


Looking at your code, this should be added to $24$.

24 + Range[-1, 4]
(*{23, 24, 25, 26, 27, 28}*)


In the loop, you also had n, running from $0$ to $5450$ in steps of $50$. We can use Table to include it.

Table[n + 24 + Range[-1, 4], {n, Range[0, 5450, 50]}]


The output of Table should be modified a bit so that Delete will use it as intended. Try a combination of Flatten and Partition.

Partition[
Flatten[Table[i + 24 + Range[-1, 4], {i, Range[0, 5450, 50]}]], 1]


Now we can just use Delete with this and we should be done.

a = Delete[data,
Partition[
Flatten[Table[i + 24 + Range[-1, 4], {i, Range[0, 5450, 50]}]],
1]];


Did this do what you wanted?

data = Range[5550];

i = 24;

Delete[data,
Flatten[
Table[{{i - 1 + n}, {i + n}, {i + 1 + n}, {i + 2 + n}, {i + 3 + n}, {i + 4 + n}}, {n, 0, 5500, 50}]
, 1]
]


This should do what you require.

todelete = {};
For[n = 0, n < 5500, n += 50,
todelete = {todelete,
{{i - 1 + n}, {i + n}, {i + 1 + n}, {i + 2 + n}, {i + 3 + n}, {i + 4 + n}}}]
todelete = List /@ Flatten@todelete;
a = Delete[data, todelete]


or, alternatively

todelete = Fold[Join[#1,
{{i - 1 + #2}, {i + #2}, {i + 1 + #2}, {i + 2 + #2}, {i + 3 + #2}, {i + 4 + #2}}] &,
{}, Range[0, 5450, 50]];
a = Delete[data, todelete]