how can sort the numbers according to the numbners in the first column

1 次查看(过去 30 天)
suppose i have a matrix where the first column is x(:,1)=[ 1 1 1 2 2 1 3 3 ] and second column is x(:,2)=[ 2 3 2 4 6 9 7 8 9];
i want different matrices which give me the numbers corresponding to 1, 2 and so on. in this case i need three different matrices where the first one will give me [2 3 2 7]
second will give [4 6] and third is [8 9]

采纳的回答

Stephen23
Stephen23 2018-11-22
编辑:Stephen23 2018-11-22
A general solution using accumarray:
>> x = [1,2;1,3;1,2;2,4;2,6;1,7;3,8;3,9]
x =
1 2
1 3
1 2
2 4
2 6
1 7
3 8
3 9
>> C = accumarray(x(:,1),x(:,2),[],@(v){v});
>> C{:}
ans =
2
3
2
7
ans =
4
6
ans =
8
9
  5 个评论
johnson saldanha
johnson saldanha 2018-11-22
now suppose i have the store the maximum, minimum and average from each cell, how can i do that and store it in the same cell but second, third and fourth column respectively.
Stephen23
Stephen23 2018-11-22
编辑:Stephen23 2018-11-22
@johnson saldanha: you could simply use a loop. Here are some alternatives:
>> fun = @(v){[min(v),max(v),mean(v)]};
>> C = accumarray(x(:,1),x(:,2),[],fun);
>> C{1} % min,max,average
ans =
2.0000 7.0000 3.5000
>> C{2} % min,max,average
ans =
4 6 5
>> C{3} % min,max,average
ans =
8.0000 9.0000 8.5000
Or you could do something a bit different, and just put the values into one matrix:
>> x = [1,2;1,3;1,2;2,4;2,6;1,7;3,8;3,9];
>> mx = accumarray(x(:,1),x(:,2),[],@max);
>> mn = accumarray(x(:,1),x(:,2),[],@min);
>> av = accumarray(x(:,1),x(:,2),[],@mean);
>> out = [x,mx(x(:,1)),mn(x(:,1)),av(x(:,1))]
out =
1.0000 2.0000 7.0000 2.0000 3.5000
1.0000 3.0000 7.0000 2.0000 3.5000
1.0000 2.0000 7.0000 2.0000 3.5000
2.0000 4.0000 6.0000 4.0000 5.0000
2.0000 6.0000 6.0000 4.0000 5.0000
1.0000 7.0000 7.0000 2.0000 3.5000
3.0000 8.0000 9.0000 8.0000 8.5000
3.0000 9.0000 9.0000 8.0000 8.5000
% x(:,1) x(:,2) max min average
But really the best solution would be to use a table, which are designed exactly to do the kind of processing that you are trying to do:

请先登录,再进行评论。

更多回答(1 个)

madhan ravi
madhan ravi 2018-11-22
编辑:madhan ravi 2018-11-22
By logical indexing you can do it:
a=x(:,1)
b=x(:,2)
first=b(a==1)
second=b(a==2)
third=b(a==3)
Note: It is assumed that x(:,1) and x(:,2) are column vectors and should contain equal number of elements because it’s extracted from a matrix and the above produces the result you need.
  5 个评论

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by