I have two arrays — an array of indices and an array of values, both are K x M. The index array has values between 1:M. Now I want to obtain the vector whose jth component is sum( valArray( indArray == j ) ).
Can you think of way to do this that beats the simple for loop solution? I have a couple of bsxfun solutions to do the ( indArray == j ) in one shot, but those don't beat the for loop. I also have a way to do this using a sparse array, but that doesn't beat the for loop either.
Here's code to set up the problem and find the answer using a for loop:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%NOTE: set M and K to be much larger for the real problem
M = 10;K = 5; indArray = randi(M,[K M]);valArray = rand([K M]);result = zeros(M,1);for ii = 1 : M * K temp = indArray(ii); result(temp) = result(temp) + valArray(ii);end
Thanks for taking a look.
Best Answer