BillyJean
BillyJean

Reputation: 1587

MATLAB: Extracting elements periodically

I'd like to extract elements from a vector using the :-operator, but periodically. As an example, say a={1,2,3, ..., 10} and that I would like to extract elements in steps of 2, changing the reference. Then I would like to get

ref 1: 1 3 5 7 9
ref 2: 2 4 6 8 10
ref 3: 3 5 7 9 1
...

Is there a keyword in MATLAB to force it to be periodic? Or do I have to apply circshift to the array first, and then extract?

Upvotes: 1

Views: 263

Answers (4)

rahnema1
rahnema1

Reputation: 15837

first concatenate two ranges [1:10] horizontally as indices to be extracted:

IDX = [1:10 1:10]

then use a function to extract n elements started from begin separated with step:

ref = @(begin,step, n) IDX(begin : step : begin+(n * step)-1 );

example:

ref(1,2,5)
ref(2,2,5)
ref(3,2,5)
ref(4,2,5)

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112699

You can build the index using a modulo operation: mod(...-1, numel(a))+1. Those -1 and +1 are needed so the resulting index is 1-based (not 0-based).

a = [1 2 3 4 5 6 7 8 9 10]; % vector to be indexed
ref = 3; % first value for index
step = 2; % step for index
ind = mod(ref+(0:step:numel(a)-1)-1,numel(a))+1; % build index
result = a(ind); % apply index

Upvotes: 4

user1543042
user1543042

Reputation: 3440

You said a vector, so I'm going to assume you meant a = [1,2,3, ..., 10]. If a is a cell, use b = cell2mat(a) and replace a with b in the code below.

I think you circshift is the best way to do this but you can do it a pretty quickly

a = 1:10;
acirc = cell2mat(arrayfun(@(n) circshift(a', [-n,0]), 0:length(a)-1, 'uni', 0))';
aout = acirc(:, 1:2:end)

This makes a matrix of a's with shifts from 0:9. Then it drops every 2nd element. Then if you want a cell array

aout = num2cell(aout,2)

Upvotes: 1

Prakhar
Prakhar

Reputation: 325

You could possibly generate two set of indices: id1 = 1:2:length(a); and id2 = 2:2:length(a);. Then you could use circshift on these indices array to get the desired arrays.

Upvotes: 1

Related Questions