how can sort the numbers according to the numbners in the first column
조회 수: 2 (최근 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에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!