Reputation: 1366
I am trying to extract a sequence of rows from a column of data in MATLAB. For example, my data looks like this in one column:
10
20
30
40
50
60
70
80
90
100
110
120
130
I want to select a sequence of rows and store these rows in a column vector A
that looks like this after extracting the first 3 rows skipping 2 rows then selecting the next 3 rows and skipping 2 rows and selecting the next 3 to the end of the column.
Finally, the data should look like this with 9 rows and 1 column
:
10
20
30
60
70
80
110
120
130
Thank you!
Upvotes: 0
Views: 213
Reputation: 1366
I just figured out another way to compliment the nice solutions using find
function.
If my data is:
x = [10; 20; 30; 40; 50; 60; 70; 80; 90; 100; 110; 120; 130]
and I want to extract a repeating sequence of rows then:
Develop an index of the repeating pattern or row sequence of keeps (3) and skips (2) rows. My index would be then:
index = [1:5 1:5 1:5]
or
index = 123451234512345
Then use the find
function to logically index the "keep" sequence.
a = find(index<4)
which gives:
a = 1 2 3 6 7 8 11 12 13
then:
b = x(a)
produces
b = 10 20 30 60 70 80 110 120 130
Upvotes: 0
Reputation: 112749
Let
x = [10 20 30 40 50 60 70 80 90 100 110 120 130].'; %'// data
m = 3; %// keep
n = 2; %// skip
Then
y = x(mod(0:end-1,m+n)<=m-1);
or equivalently
y = x(mod(0:numel(x)-1,m+n)<=m-1);
How this works: generate the sequence 0,1,2,... numel(x)-1
. Each number corresponds to a position in x
. To keep m
and skip n
cyclically, you apply mod(...,m+n)
to that sequence. For example, for m=3
, n=2
the result is sequence 0,1,2,3,4,0,1,2,...
. You then select those numbers (that is, the corresponding entries of x
) that are <=m-1
. This results in the periodic pattern "keep, keep, keep, skip, skip".
To first skip and then keep (reverse from above): just reverse the inequality:
y = x(mod(0:end-1,m+n)>=m-1);
or
y = x(mod(0:numel(x)-1,m+n)>=m-1);
Upvotes: 2
Reputation: 221614
Try this, assuming a
is your input column vector -
r_accept = 3; %// number of rows to accept
r_reject = 2; %// number of rows to reject
ind1 = bsxfun(@plus,1:r_accept+r_reject:numel(a),[0:r_accept-1]') %//'
out = a(ind1(ind1(:)<=numel(a))) %// desired output
Upvotes: 1