Reputation: 118
I am trying to vectorise a for loop that sums a vector to a index defined by another vector. There are a large number of vectors to sum. This is done easily in a for loop but perhaps not obviously to me, in a vectorised manner.
An random example would be:
t = rand(10, 5);
c = randi([1 5], 1, 10);
Basically, I now need to sum across each row until the corresponding column given by the same index of c as current row t. The return value would be a vector of the row sum to its respective column c(i). I have explored as many manipulations of the sum function that I can think of but none achieve the end result.
Any advice?
Upvotes: 1
Views: 37
Reputation: 112659
One way to do that is using bsxfun
to create a mask of the values that you want to include in each row sum:
result = sum(t .* bsxfun(@le, 1:size(t,2), c(:)), 2);
In Matlab R2016b or newer you can use implicit expansion instead of bsxfun
:
result = sum(t .* (1:size(t,2) <= c(:)), 2)
Upvotes: 1