MATLAB Answers

Niraj Poudel

Sorting and Saving a subset from the array

Asked by Niraj Poudel
on 29 Dec 2012

Hi there,

I have imported data from Excel and now have a 240X3 cell array called 'num'.

Once sorted it looks something like this:

16 1232 56

16 3455 56

16 5443 76

16 1232 88

17 4545 65

17 3432 87

All I want to do is for to write a for loop to select all rows of the data which start with 16's and then save it as another array say num_1, then take another chunk that starts with 17's and save it as num_2..etc.

How can I compose a for loop to take care of that. I have tried different measures based on other questions here in matlab central but to no avail.

Any help will be appreciated.

Sincerely yours; Nj



2 Answers

Answer by Walter Roberson
on 29 Dec 2012

unum = unique(num(:,1));
for K = 1 : length(unum)
  these_num = num(num == unum(K), :);
  num_{K} = these_num;

This will create num_{1}, num_{2} and so on. Creating actual new variables is not a good idea; see

  1 Comment

Hi Walter, Thank you for your prompt response. However when I run the code you just sent me, it keeps telling me that the index exceeds matrix dimensions, plus I do not see anywhere in the code where I can specify the rows starting with 16 and 17 and so forth?

Am I missing something? Any help will be appreciated. Nj

Answer by Andrei Bobrov
on 29 Dec 2012
Edited by Andrei Bobrov
on 29 Dec 2012

a0 = {16 1232 56
16 3455 56
16 5443 76
16 1232 88
17 4545 65
17 3432 87};
a = cell2mat(a0);
[b,~,c] = unique(a(a(:,1)>=16,1));
num = ...


For some reason this does not work either. In this code there does not seem anywhere that rows starting with 16 should be saved as a different array? And 17 and 18 and so forth? I might be wrong. please correct me if I am so. Thank you for your response.


Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!