How to delete multiple rows from a table using a for loop (with a condition)?

32 views (last 30 days)
Hasnain Raja Muhammad on 2 Sep 2021
I would like to delete multiple rows form a table (imported from Excel).
I have "n" number of rows with 5 columns (Var1,..........,Var5). Now if in column 5 (Var5), there is value greater than 0, I want that row and the next three rows to be deleted.

Jeremy Hughes on 2 Sep 2021
I wouldn't use a for loop. MATLAB excells at array operations.
A = randn(12,5); % Make some data with positive and negative values
A(1:4:5) = -abs(A(1:4:5));
A(end-4:end) = -abs(A(end-4:end));
T = array2table(A)
T = 12×5 table
A1 A2 A3 A4 A5 _________ ________ ________ ________ ________ -0.18657 0.76498 0.23522 -0.86791 0.35787 0.74813 0.73723 -0.13228 0.05872 -1.1772 1.4034 -1.6129 -0.55285 2.2033 0.20268 0.91163 0.915 -1.3487 -0.31358 0.16887 -1.3759 1.4728 0.98564 -1.0473 0.34148 -0.68973 -0.28485 -0.98694 0.29496 1.4129 2.4566 -0.9063 -1.3356 -1.1073 2.1731 -0.068694 -0.3263 0.90646 -0.19821 -1.1389 1.1861 1.0306 3.1811 -2.0224 -0.60713 -0.044051 -0.62426 0.72973 -0.58808 -0.66111 0.46205 0.12273 1.0989 0.013466 -1.363 -0.63828 0.81857 -0.54734 0.59388 -0.76208
rowIdx = find(T.A5 > 0);
rowIdx = rowIdx(:) + (0:3); % expands column + row
T(rowIdx,:) = [] % deletion
T = 2×5 table
A1 A2 A3 A4 A5 ________ _______ ________ ________ ________ 0.46205 0.12273 1.0989 0.013466 -1.363 -0.63828 0.81857 -0.54734 0.59388 -0.76208
You can also only check every fourth row, but there's some tricky math.
rowIdx = find(T.A5(1:4:end) > 0) % check every 4th entry will result in the "block" index though
rowIdx = 4*(rowIdx-1)+1; % re-align to the right places in the original array
rowIdx = rowIdx(:) + (0:3); % expands column + row
T(rowIdx,:) = [] % deletion
T = 2×5 table
A1 A2 A3 A4 A5 ________ _______ ________ ________ ________ 0.46205 0.12273 1.0989 0.013466 -1.363 -0.63828 0.81857 -0.54734 0.59388 -0.76208
Hasnain Raja Muhammad on 3 Sep 2021
Thanks, it works perfectly fine!

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

R2018a

Community Treasure Hunt

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

Start Hunting!