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!