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

조회 수: 1 (최근 30일)
Hung Dao
Hung Dao 2021년 2월 23일
댓글: Hung Dao 2021년 2월 23일
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.

답변 (1개)

Walter Roberson
Walter Roberson 2021년 2월 23일
cumsum() and index it by the values
  댓글 수: 6
Hung Dao
Hung Dao 2021년 2월 23일
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 2021년 2월 23일
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?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by