Reputation: 193
I am going to select some rows of a data set, except of a list of indices.
For example, in a given data_set
I want to select all rows except for idx = [2,3,6,11,15]
.
How can we do this in MATLAB? Is there any command or logical indexing method?
Upvotes: 2
Views: 370
Reputation: 30165
There are many ways to do this by comparing your exclusion list with a full list from 1:n
, where n
is the number of rows. Below I've listed 2 which use this logic. I've also shown the simplest way (removing rows) but that requires an intermediate step.
I'm not sure which is more performant of these:
% Setup
idx = [2,3,6,11,15]; % exclusion list
M = rand( 25, 10 ); % test matrix to index (25 rows)
Using ismember
and logical indexing
K = M( ~ismember( 1:size(M,1), idx ), : );
Using setdiff
to get the row numbers not listed
K = M( setdiff( 1:size(M,1), idx ), : );
Creating a temp matrix, then removing the excluded rows
K = M;
K( idx, : ) = [];
Error handling
Note that the final row-removing method will produce an error if any of the rows in your exclusion list are out of bounds (e.g. if 0
was in idx
).
The setdiff
and ismember
methods won't give you any errors, the presence of out-of-bounds values in idx
are simply redundant.
Upvotes: 3