How to delete multiple rows from a table using a for loop (with a condition)?
10 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Jeremy Hughes
2021-9-2
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)
rowIdx = find(T.A5 > 0);
rowIdx = rowIdx(:) + (0:3); % expands column + row
T(rowIdx,:) = [] % deletion
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!