Delete row from matrix given an id- Matlab

天大地大妈咪最大 提交于 2019-12-24 15:04:16

问题


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?


回答1:


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.




回答2:


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,:);


来源:https://stackoverflow.com/questions/28150143/delete-row-from-matrix-given-an-id-matlab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!