How do I create a vector of n consecutive numbers spaced at with an interval of m between each group, without using a for loop?

18 ビュー (過去 30 日間)
Is it possible to generate the following vector:
v=[1,2,3 ,6,7,8 ,11,12,13 ....]
without using a for loop? More generally, I would like to be able to generate groups of n consecutive numbers with an interval of m between each group (in the example n=3 and m=2).
Thank you in advance..

採用された回答

Guillaume
Guillaume 2018 年 6 月 18 日
編集済み: Guillaume 2018 年 6 月 18 日
numconsecutive = 3; %let's use better names than n, m, etc.
groupspacing = 2;
numgroups = 5;
v = reshape((1:numconsecutive)' + (0:numgroups-1)*(numconsecutive+groupspacing), 1, [])
This requires R2016b or later

その他の回答 (1 件)

Honglei Chen
Honglei Chen 2018 年 6 月 18 日
編集済み: Honglei Chen 2018 年 6 月 18 日
Here is one possible solution
N = 9;
n = 3;
m = 2;
x = buffer(1:N,n);
x = x+(0:size(x,2)-1)*m;
x(1:N).'
HTH
  1 件のコメント
Seb Long
Seb Long 2018 年 6 月 18 日
Many thanks for your answer! This works fine but I accepted the answer above as it runs faster. Thanks again..

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

カテゴリ

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

タグ

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by