calculate the frequency of element in a matrix
4 views (last 30 days)
Show older comments
matrix = [1 1 1 1 4 5 5 7 14 14 14 14 14 15 15 15 17 17 ; 2 6 7 7 7 2 3 5 2 3 4 5 6 3 4 4 3 6 ; 7 7 5 7 6 3 2 5 6 6 7 6 3 3 2 5 5 5 ; 0 0 1 0 0 1 0 1 0 0 0 0 1 1 1 1 1 1]
I don't know how i can calculate how many times a number appears in the first row and at the same time calculate how many times a one appears in the fourth row when the element in the first row remains the same. For example my desired output would be:
matrix2 = [1 4 5 7 14 15 17 ;
4 1 2 1 5 3 2 ;
1 0 1 1 1 3 2]
1 Comment
Jan
on 22 May 2015
It would be more convenient, if you post the data in a format, which can be used by copy and paste. It is much easier to provide code, when we can test it.
Accepted Answer
Andrei Bobrov
on 23 May 2015
matrix1 = [1 1 1 1 4 5 5 7 14 14 14 14 14 15 15 15 17 17 ;
2 6 7 7 7 2 3 5 2 3 4 5 6 3 4 4 3 6 ;
7 7 5 7 6 3 2 5 6 6 7 6 3 3 2 5 5 5 ;
0 0 1 0 0 1 0 1 0 0 0 0 1 1 1 1 1 1];
[a,~,c] = unique(matrix1(1,:));
[jj,ii] = ndgrid(c,1:2);
out = [a;accumarray([ii(:),jj(:)],[ones(size(matrix1,2),1);matrix1(4,:)'])];
0 Comments
More Answers (1)
Jan
on 22 May 2015
Edited: Jan
on 22 May 2015
[B, N, BI] = RunLength(matrix(1, :));
V = RunLength(1:length(B), N);
K = accumarray(V.', matrix(4, :).').';
Result = [B; N; K];
2 Comments
Jan
on 23 May 2015
Did you see the "with FEX: RunLength" link? Follow the link to get the code for RunLength. You find a fast MEX-function there, which requires a compilation. If speed does not matter that much, use RunLength_M from this submission.
See Also
Categories
Find more on String Parsing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!