Click to See Complete Forum and Search --> : Matlab - Retrieving a subset of a matrix


denno
April 4th, 2005, 04:14 PM
Given the matrix [x x 1; x x 1; x x 2; x x 2; x x 3; x x 3]

How can I reduce the matrix to only contain those rows with 1 in the third column, so I have the resulting matrix [x x 1; x x 1]?

I know that I can do this using a loop, but given that MatLab is intended for matricies, I'm thinking that there is a much easier (and faster) method of accomplishing this. Loops take a while in MatLab and I'm generally dealing with a lot of data.

I'm also wondering if there's a way to only plot this subset using the original matrix as an input. This isn't necessary if I can generate the subset, but it would be nice to know.

Anyway, thanks to anyone who can provide any help.

denno
April 8th, 2005, 08:36 AM
I've found a solution.

Take the matrix and sort on the given field. Once the field is sorted, use the unique function to return the last instance of each value. Then plot any value based on the limit (returned from the unique function) of the value you want to plot and the the limit of the value just before the one that you want to plot. This worked well for me and was exceptionally quick.

yiannakop
April 8th, 2005, 10:22 AM
I don't get excactly what you mean, but I am sure there is a simple way to do what you ask in your 1st thread. Suppose you have a 6x3 matrix, like in your example. Then, to have only the 1st 2 lines (those with 1 as last element) you can simply write:

y = x(find(x(:,3)==1),:)

Then y is matrix: [x x 1;x x 1]
Hope it helps. :wave:
Regards,
Theodore