MATLAB: How to extract differnt size submatrices out of a larger one using a for loop

extract matricesvlookup

Hi,
I have a matrix 3 by 862 representing the results of 5 samples stacked vertically. The samples are all of different sizes. The columns are 1) Sample ID (ID), 2) Depth (D) and 3)Turbidity (T). eg.
ID D T
- - -
- - -
n n n
I would like to extract the 5 samples into their own matrices using the first column ID to separate them similar to the Vlookup function in excel so I can then conduct subsequent calcs. I know how to manually extract samples, using:
S1=ID==1;
D1=D(S1);
T1=T(S1);
Summary=[D1 T1]
To extract sample 1, however, I am looking for a way to automate this. i.e. extract all the samples at the same time and ideally the ability to handle different numbers of samples. I think I need to loop, but can not get it to work and am becoming confused because not other examples that I have found rely on using one column (ID in my case) to separate and then extract other data based on this.
Thanks Matt

Best Answer

Presuming the answer to question above is "yes", you've got the right idea; as for processing multiple you simply make the ID a variable instead of a constant. If the numbers aren't sequential and known a priori, unique is one good way to build the iterator set--
IDs=unique(D(:,1)); % unique IDs in the set
for i=1:length(IDs)
ix=D(:,1)==IDs(i); % logical over ith ID
res=yourprocessingfunction(D(ix,2),D(ix,3));
% do whatever with the results for this case here
...
end
The above is for a function written with two arguments for the two variables, you could also create it to handle an [X Y] array as you wrote above simply but recasting just a little--
res=yourprocessingfunction(D(ix,2:3));
which simply selects the two columns concurrently.
The differing sizes comes along "for free, automagically" in the result of the selection of the matching items; if need to know that you simply use size or otherwise query the result to ascertain what that number is. Note that sum(ix) will be that number as one alternate way amongst many.
Or, of course, there are selection tools built into the dataset object that can be used if cast the original data into that form instead of just the array.