Lasse
Lasse

Reputation: 47

Matlab: How do I remove rows that contain any of the numbers stored in a vector?

I have 163x2 matrix called A, and a 15x1 vector called delindex. Now I want to delete every row from A, that has any of the numbers stored in delindex as a value in the first row.

short example:

A =

           1       29292
           2       44652
           3       56569
           4       68909
           5       81053
           6       93343
         101      105585
         102      118870
         103      132163
           7      144257
         104      156616
           8      205344
           9      216865
         105      228979
         106      229307
         107      240849
         108      253306

And my delindex =

4
101
7
105

(And for possible future implications: how do I do the same for other rows, in this example the seconde one?)

I have looked up removerows and the any() function, but can't get them to work for me. I'm totally new to matlab and programming, so a place to look in documentation on this might help me as well!

Thanks in advance!

Upvotes: 2

Views: 164

Answers (1)

p8me
p8me

Reputation: 1860

Use ismember (@Prashant's suggestion):

ia = ismember(A(:,1), delindex);

Or intersect:

[~,ia,~] = intersect(A(:,1), delindex);

To find which rows should be removed. Then remove the rows:

A(ia,:) = []

Note

ismember returns logical indices, while in [C,ia,ib] =intersect(A,B), ia and ib are indices.

Both could be used for indexing. For more info read Matrix Indexing in MATLAB.

Upvotes: 2

Related Questions