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?

Answers


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.


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

Need Your Help

Is following statement valid in ANSI C? Is it valid at all?

c language-lawyer c89 sequence-points

During my preparation to exam on ANSI C I have encountered the following question -

Proper way to maintain client http client-server connection?

java android google-app-engine servlets client-server

I'm trying to build an Android application in which the client authenticating to the server from the application and after the auth the client sends and receives messages from the server.

How do I open a file in its default program

c windows winapi

How do I programmatically open a file in its default program (I'm using Windows XP).

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.