Is there a better way to perform a moving window of operations without using a for loop?

2 ビュー (過去 30 日間)
Say I have a matrix:
x=1:100;
And I want to create a new matrix y that has the following output:
[sqrt(1^2+4^2), sqrt(2^2+5^2), sqrt(3^2+6^2), ... etc.]
Note that each term in the output is y[index]=sqrt(x[index]^2+x[index+3]^2).
I could accomplish this with a for loop, but if matrix x is really large this is inefficient. Is there a more efficient way?

採用された回答

John Chilleri
John Chilleri 2017 年 9 月 6 日
編集済み: John Chilleri 2017 年 9 月 6 日
Hello,
You can figure out a way to use vector notation,
x = 1:100;
y = sqrt(x(1:end-3).^2+x(4:end).^2);
I ran this vs the for loop version you have above, and this performed twice as fast when x = 1:1000000 and three times faster when x = 1:100000000. Although it didn't take long for either, I'd be more concerned for memory than speed - but that's only regarding this problem.
Hope this helps!
  2 件のコメント
razorfin
razorfin 2017 年 9 月 7 日
Thanks, this is exactly what I was looking for, but I just couldn't seem to think in this way. I'll remember it for the future!
John Chilleri
John Chilleri 2017 年 9 月 10 日
Glad I could help!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by