フィルターのクリア

How do I efficiently iterate over subvectors of a given vector?

1 回表示 (過去 30 日間)
Daniel Pollard
Daniel Pollard 2020 年 12 月 4 日
編集済み: Daniel Pollard 2020 年 12 月 4 日
I have a vector of length N, which I want to generate all possible subvectors of of length n and sum over the subvectors. At the minute I have written
for val = 1:(N-n)
sums(val) = sum(vector(val:(val+n)))
end.
For example, if vector = [1, 2, 3, 4] and n=2, then this would return
sums = [3, 5, 7].
However, this code isn't very efficient. I'm aware of the buffer function in the Signal Processing toolbox, and using this speeds up my code by around a factor of 4, but I'm trying to avoid toolbox functions as I'm aiming to use Matlab Coder to translate into C code, which doesn't understand toolbox functions as far as I'm aware.
Is there a more efficient way to do this, possibly without using the for loop? I've done as much as I can with my knowledge, for example preallocating the sums vector, but I'm not sure how else to improve it.

採用された回答

Walter Roberson
Walter Roberson 2020 年 12 月 4 日
  1 件のコメント
Daniel Pollard
Daniel Pollard 2020 年 12 月 4 日
That's worked perfectly. Exactly what I was after, but couldn't find the right Google phrase to find it. Thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeNumeric Types についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by