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]
0 个评论
采纳的回答
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 个评论
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
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 个评论
madhan ravi
2018-11-22
result=cell(1,n) %before loop
result{i}=a(b==i); %inside loop
celldisp(result) %outside loop
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!