Aggregate Data in a large matrix using unique identifiers.
1 次查看(过去 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!