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!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With