Grouped elements in a matrix in matlab -


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?

  1. standard, recommended approach: use unique , histc:

    ua = unique(a); result = [ua; histc(a, ua)]; 
  2. another possibility counting sparse, , use nonzeros 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

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -