Info

此问题已关闭。 请重新打开它进行编辑或回答。

Shall I extract data from Matrix by group seperately?

1 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2016-1-5
编辑:Stephen23 2016-1-5
"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:

回答(1 个)

the cyclist
the cyclist 2016-1-5
编辑:the cyclist 2016-1-5
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.

此问题已关闭。

Community Treasure Hunt

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

Start Hunting!

Translated by