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

1 回表示 (過去 30 日間)
johnson saldanha
johnson saldanha 2018 年 11 月 22 日
編集済み: Stephen23 2018 年 11 月 22 日
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 件のコメント
madhan ravi
madhan ravi 2018 年 11 月 22 日
result=cell(1,n) %before loop
result{i}=a(b==i); %inside loop
celldisp(result) %outside loop
johnson saldanha
johnson saldanha 2018 年 11 月 22 日
thanks

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by