How to delete multiple rows from a table using a for loop (with a condition)?
10 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hasnain Raja Muhammad
le 2 Sep 2021
Commenté : Hasnain Raja Muhammad
le 3 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.
0 commentaires
Réponse acceptée
Jeremy Hughes
le 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)
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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!