Aggregate Data in a large matrix using unique identifiers.
조회 수: 2 (최근 30일)
이전 댓글 표시
Hello Matlab world, I hope everyone is doing really well. I have a large matrix and I need to aggregate the data in based on unique identifiers from the matrix's first column ( grouping the data by unique identifiers) . Example:(5*4) Matrix A=
A=[5 2 1 3;
4 3 7 5;
5 1 1 1;
3 1 2 7;
4 1 5 8]
So the desired matrix should be (3*3) and that is by aggregating rows based on common identifiers from the first column.
B=[3 1 2 7;
4 4 12 13;
5 3 2 4];
I also need to know the frequency of each unique identifier (i.e., 4 and 5 both appear twice) so I can get the average in each row. I hope I was clear, Thank you so much
Below is a code that I used earlier:
[a,~,c] = unique(MAVGS_S(:,1)); %extract unique values of the indicator column
out(:,1)=a; % assign the unique values extracted to the first column of the output table
% loop for all the columns to compute summary statistics according to the unique values
by_col = [a, accumarray(c,MAVGS_S(:,2))]; % extract (unique values in first column and summary statistics in the second column for each column
out(:,2)=by_col(:,2); % extract the summary statistics for i column to the output table;
Acc_COST=[out]; %The matrix containing the aggregated data at the CBG level. (758*102)
%Count how many 1km*1km Pixels in each census block group.
[x,y]=hist(MAVGS_S(:,1),unique(MAVGS_S(:,1)));
Pixels_Count=x';
댓글 수: 0
답변 (1개)
Guillaume
2016년 10월 24일
편집: Guillaume
2016년 10월 24일
A=[5 2 1 3; 4 3 7 5; 5 1 1 1; 3 1 2 7; 4 1 5 8];
[ids, ~, subs] = unique(A(:, 1));
B = [ids, cell2mat(accumarray(subs, 1:size(A, 1), [], @(rows) {sum(A(rows, 2:end), 1)}))]
idcount = accumarray(subs, 1)
is how I would do it.
댓글 수: 2
Guillaume
2016년 10월 24일
Oops, sorry. I thought I tested the code. It was missing the empty array for size. Fixed now.
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!