How to delete all rows of a matrix wherever any value is invalid (999)?
6 views (last 30 days)
Show older comments
I have a matrix M of 100 rows and 4 colums.
Whenever column 1 of M is 99 I want to delete the entire row. Also whenever column 4 of M is 999 I want to delete the entire row.
I tried idx = any((M(:,1)==99),2); M(idx,:) = [];
but it did not work
0 Comments
Answers (3)
Awais Saeed
on 11 Nov 2021
M = [99 1 25 999; 10 1 2 6; 14 99 25 65; 99 1 2 9; 9 1 999 10]
[row1,~] = find(M(:,1) == 99) % search for 99 in col1
[row2,~] = find(M(:,4) == 999)% search for 999 in col4
del_row = unique([row1;row2]) % remove duplicate row numbers
M(del_row,:) = [] % delete those rows
0 Comments
Steven Lord
on 11 Nov 2021
Let's make a sample matrix M with some 999 values present in columns 1 and 4. I'll also make a backup copy of it so we can modify the original several times, restoring from the backup each time.
M = randi(10, 10, 5);
M([2 7], 1) = 999;
M([3 7], 4) = 999;
backupM = M;
disp(M)
Now let's approach this in three different ways. The first creates variables for each column to check (though this could be combined into one command, replacing column1Has999 and column4Has999 with the right-hand side expression in the line of code that creates the variable eitherColumnHas999.
column1Has999 = M(:, 1) == 999 % should indicate rows 2 and 7
column4Has999 = M(:, 4) == 999 % should indicate rows 3 and 7
eitherColumnHas999 = column1Has999 | column4Has999 % should indicate rows 2, 3, and 7
M(eitherColumnHas999, :) = [] % rows 2, 3, and 7 have been removed
But if you want to check a large collection of columns that's going to be a lot of repetitive code. Instead you could use any.
M = backupM; % restore from backup copy
columnsToCheck = [1 4];
checkedColumnsHave999 = any(M(:, columnsToCheck) == 999, 2) % rows 2, 3, and 7
M(checkedColumnsHave999, :) = []
A third option would be to standardize the representation of missing data in M using standardizeMissing and then to use rmmissing.
M = backupM; % restore from backup
M = standardizeMissing(M, 999) % Convert 999 to the "standard" missing for double, NaN
M = rmmissing(M, 1) % Eliminate rows that contain a missing value
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!