Shall I extract data from Matrix by group seperately?

Now I have a matrix as below:
z =
1.0000 -7.6365
2.0000 1.7736
3.0000 -11.1412
4.0000 -10.1350
5.0000 0.9315
1.0000 16.3263
2.0000 -6.6967
3.0000 4.7138
4.0000 -1.2558
5.0000 12.1736
1.0000 6.4000
2.0000 4.5000
3.0000 3.5000
I can use function-'sort' to deal with it as below:
sortrows(z)
ans =
1.0000 -7.6365
1.0000 6.4000
1.0000 16.3263
2.0000 -6.6967
2.0000 1.7736
2.0000 4.5000
3.0000 -11.1412
3.0000 3.5000
3.0000 4.7138
4.0000 -10.1350
4.0000 -1.2558
5.0000 0.9315
5.0000 12.1736
Now I want to get the data like below:
n1=
-7.6365
6.4000
16.3263
n2=
-6.6967
1.7736
4.5000
n3=
-11.1412
3.5000
4.7138
n4=
-10.1350
-1.2558
n5=
0.9315
12.1736
How shall I get n1,n2,n3,n4,n5 better and what if I want to get n1,n2,...n100?

3 Comments

When you do the sort, do you really want to sort each columns independently, or did you mean to keep rows intact? If the latter, you want to use the sortrows command.
yes, just as you guess; Thanks for your reminding.
"How shall I get n1,n2,n3,n4,n5 better and what if I want to get n1,n2,...n100?"
Don't
You really don't want to do this. It is poor way to program and will make your programming buggy, slow and complicated. If you want to know why, then read about it here:

Answers (1)

Here's one way:
z= [1.0000 -7.6365
2.0000 1.7736
3.0000 -11.1412
4.0000 -10.1350
5.0000 0.9315
1.0000 16.3263
2.0000 -6.6967
3.0000 4.7138
4.0000 -1.2558
5.0000 12.1736
1.0000 6.4000
2.0000 4.5000
3.0000 3.5000];
sorted_z = sortrows(z,[1 2]);
[uz, ~, j] = unique(sorted_z(:,1));
numberUnique = numel(uz);
n = cell(numberUnique,1);
for nu = 1:numberUnique
indexToThisValue = (j==nu);
n{nu} = sorted_z(indexToThisValue,2);
end
Your vectors are stored in the elements of the cell array: n{1}, n{2}, etc.
This is much better than storing them in individual variables n1, n2, etc. You can read about that in many threads in this forum.

This question is closed.

Asked:

on 5 Jan 2016

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!