An efficient way to compute many sums with different number of terms

1 view (last 30 days)
Suppose I have 2 functions and .
Given different values of , define
and
.
For each , I want to compute the sums (if ) or (if ) where and ϵ are given.
The number of terms varies across elements. For example,
I have then I need to compute 10 terms which are or then sum them up.
I have then I only need to compute 2 terms which are or then sum them up.
If the number of terms are all the same, i.e., , then I think I can vectorize and handle the computation. However, since the length of the sums are not the same, it becomes more difficult for me to handle it efficiently.
Can you help me to compute this in an efficient way?
Thank you very much in advance.

Answers (1)

Walter Roberson
Walter Roberson on 23 Feb 2021
cumsum() and index it by the values
  6 Comments
Hung Dao
Hung Dao on 23 Feb 2021
Thank you very much. I implement your code and it works.
However, it might be very inefficient if there only a few that are very large (say 10,000 or more) and the other κ's are small. This is exactly the case which I am dealing with.
I am wondering whether a for loop might be more efficient in this case.
Hung Dao
Hung Dao on 23 Feb 2021
In fact, what I am doing is to set then do the vectorization. I think it's quite similar to your suggestion. But the problem is that it is unnecessarily expensive. In principle, I can reduce the amount of computation by determining the optimal for each . However, this makes an efficient coding become much more challenging for me. I could use a for loop but it is the worst solution since I already have 2 for loops nested.
Is there any trick or Matlab function that I can use to handle this efficiently?

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!