user3630879
user3630879

Reputation:

Extract equally spaced subarrays from an array

I have an array:

v = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20];

I want to extract multiple arrays of length 3 equally spaced by 6 elements, starting at the fifth element of v, and then combine them together:

v1 = [5 6 7];
v2 = [11 12 13];
v3 = [17 18 19];

v_combined = [5 6 7 11 12 13 17 18 19];

Are there any simple ways to do this without using a for loop?

Upvotes: 0

Views: 75

Answers (2)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

In general for m elements spaces by n elements starting from k you can use

k=5;
m=3;
n=6;

I=1:numel(v);
v_combined = v((I>=k) & mod(I-k,n)<m)

Upvotes: 1

Dan
Dan

Reputation: 45752

You can do it using logical indexing. You need to create an index mask like this

idx = [0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 0 1 1 1 0]

which you can create like this:

idx = false(size(v))
k = 5
idx(k:end) = ~mod(floor((0:numel(v)-k)/3),2)

And finally

v_combined = v(idx)

Upvotes: 3

Related Questions