문제

I have a matrix like the following:

A =    
     250         700         950
      81        1630        1711
     250         700         950
      81        1630        1711
     250         700         950
      81        1630        1711
     250         700         950
      81        1630        1711
     250         700         950
      81        1630        1711
     250         700         950
      81        1630        1711
     250         700         950
      81        1630        1711
     250         700         950

I want to produce a new matrix like this:

B = 

      81        1630        1711           7
     250         700         950           8

containing a row for each unique row in the original matrix, and a fourth column containing the number of times that row appears in the original matrix.

I can use unique(A,'rows'), but I don't know how to create the fourth column containing the number of appearances. I know unique has three possible arguments, and I think that may be the way to do this, but couldn't figure it out from the documentation.

도움이 되었습니까?

해결책

You can get the fourth column by manipulating the second and third outputs of unique:

[C,IA,IC] = unique(A,'rows');
counts = sum(bsxfun(@eq,IC,IA.')).';
C = [C counts(IA)]

Or if you also use the 'stable' option of unique, then the counts do not need to be reordered (C = [C counts]).

OR you can use my favorite function, accumarray:

C = [C accumarray(IC,1)]

다른 팁

You can also use sortrows:

As = sortrows(A);
ind = [ find(any(diff(As).')) size(As,1) ];
B = [ As(ind,:) diff([0 ind]).' ];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top