Amira Akra
Amira Akra

Reputation: 163

Delete row from matrix given an id- Matlab

How can I delete a certain row from a matrix depending on the 1st column value?

For example: A=[1 2 3;3 4 5;5 6 7] where the values of the first column represent the ids and I want to delete the row that has 5 as an id. I already know that A(3,:)=[] deletes the third row, but what if I have the id and don't know the row number?

Upvotes: 1

Views: 199

Answers (2)

Divakar
Divakar

Reputation: 221564

If you have only element as id, then I would go with @yoh.lej's solution. But, if you happen to have an array of elements as id, you can use one of the approaches listed next.

Approach # 1 (With ismember)

A(ismember(A(:,1),ids),:) = [];

Approach # 2 (With bsxfun)

A(any(bsxfun(@eq,A(:,1),ids(:)'),2),:) = [];

If the first column of A has unique ids, then you have two more approaches to play with.

Approach # 3 (With intersect)

[~,remove_rowid] = intersect(A(:,1),ids);
A(remove_rowid,:) = [];

Approach # 4 (With setdiff)

[~,select_rowid] = setdiff(A(:,1),ids,'stable');
A = A(select_rowid,:);

Upvotes: 1

yoh.lej
yoh.lej

Reputation: 1104

You can use find:

id=5;
A(find(A(:,1)==id),:)=[]
A =

 1     2     3
 3     4     5

Note that, as mentioned by Divakar, thanks to logical indexing you can even omit the find:

A(3,:)

and

A(logical([0 0 1]),:)

are equivalent so

A(find(A(:,1)==id),:)=[]

and

A(A(:,1)==id,:)=[]

will give the same result.

Upvotes: 1

Related Questions