how can sort the numbers according to the numbners in the first column
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
johnson saldanha
el 22 de Nov. de 2018
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 comentarios
Respuesta aceptada
Stephen23
el 22 de Nov. de 2018
Editada: Stephen23
el 22 de Nov. de 2018
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 comentarios
Stephen23
el 22 de Nov. de 2018
Editada: Stephen23
el 22 de Nov. de 2018
@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:
Más respuestas (1)
madhan ravi
el 22 de Nov. de 2018
Editada: madhan ravi
el 22 de Nov. de 2018
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 comentarios
madhan ravi
el 22 de Nov. de 2018
result=cell(1,n) %before loop
result{i}=a(b==i); %inside loop
celldisp(result) %outside loop
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!