Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining a matrix of values and indices in MATLAB

Tags:

matlab

I have a matrix of indices such as indices = [1,3,1 ; 2,4,2 ; 1,3,1].
I have a matrix of values such as values = [5,9,2 ; 3,4,1 ; 6,8,7].
I want to create a new matrix combined = [5+2+6+7,9+8 ; 3+1,4] without using a for loop. "Combined" should consist of the elements of the matrix "values" added together based on what their respective indices are in the matrix "indices."
Do you have any suggestions how to approach this in MATLAB? Thank you in advance!

like image 472
user2271276 Avatar asked Nov 13 '22 07:11

user2271276


1 Answers

You can use GRPSTATS function from Statistical Toolbox:

val = [5,9,2 ; 3,4,1 ; 6,8,7];
idx = [1,3,1 ; 2,4,2 ; 1,3,1];

result = grpstats(val(:),idx(:),'sum');
result = reshape(result, 2, 2);
like image 83
yuk Avatar answered Nov 15 '22 08:11

yuk