subsetting elements in one matrix by those in a smaller vector

Hi,
I have a matrix X which is 15000 rows and 150 columns. I have a vector Y which is 10 rows by 1 column. Say the values of X(:,3) range from 10:1:30. Each of those values might be the same for, say, 200 rows or so before jumping up a number. In Y, I have discontinuous values which might be [10;11;14;16;20;24;29;30] (for example). I want to create a new matrix C of all the rows which match each number from Y.
Pretty much every solution I've tried has failed. The best I can come up with that actually does what I want is this:
Cn.v10 = X((X(:,3)==10),:);
Cn.v11 = X((X(:,3)==11),:);
Cn.v14 = X((X(:,3)==14),:);
C = cat(2,Cn.v10,Cn.v11,Cn.v14);
But this seems like the stupidest and most time consuming way possible, and I've got loads of values to go through. I've tried ismember and any, plus logical indexing etc. Nothing has properly worked.
I feel like the solution should be obvious but I just can't make it fit.
Sorry for being dumb. Any help?
S.

1 Comment

This is not clear for me. Give a small numeric example with expected result

Sign in to comment.

Answers (1)

p = [10;11;14;16;20;24;29;30];
[l,ii]=ismember(X(:,3),p);
i2 = sort(ii);
x1 = X(l,:);
out = mat2cell(x1(i2,:),histc(i2,unique(i2)),size(X,2));

2 Comments

Hi, Thanks. I'm assuming i1 and jj are both typos for ii? I just can't see what to use instead if they aren't. Unfortunately this didn't work, even with corrections: got the usual "Subscript indices must either be real positive integers or logicals" error.
Hi Sara! My typo. Corrected.

Sign in to comment.

Asked:

on 9 Sep 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!