Grouped elements in a matrix in matlab -
this question has answer here:
i have matrix a = [1 2 4 4 8 8 8 4 1 7 7 8 8 9]
, want create new matrix has number of same elements in a.
i have 2 1, 1 2, 3 4, 2 7, 5 8 , 1 9.
my new matrix should [numbers;amount of each number]
newmatrix = [1 2 4 7 8 9; 2 1 3 2 5 1]
how can create new matrix a?
standard, recommended approach: use
unique
,histc
:ua = unique(a); result = [ua; histc(a, ua)];
another possibility counting
sparse
, , usenonzeros
extract values ,find
indices:s = sparse(1,a,1); result = [find(s); nonzeros(s).'];
this second approach seems faster small
a
, first recommended approach in general.
Comments
Post a Comment