A_Man_Has_No_Name
A_Man_Has_No_Name

Reputation: 118

Summing rows to arbitrary columns in Matlab

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

Answers (1)

Luis Mendo
Luis Mendo

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

Related Questions