3

I am attempting to set up some code to extract certain elements of a matrix, and keeping only these values in another matrix, in the order they were extracted.

Example: If I have a random 1X20 matrix, but want only every Nth = 5th element beginning with 4 and 5, I would want it to construct a new matrix (1x8) consisting only of 4, 5, 9, 10, 14, 15, 19, 20.

What I have so far is:

r = rand(1,20);
n = 5;
a = r(4 : n : end);
b = r(5 : n : end);

So instead of two separate matrices, I instead want one matrix in its original chronological order (again, a 1x8 matrix consisting of the elements in the order of 4,5,9,10,14,15,19,20). Essentially, I'd like to be able to do this for any number of values while still maintaining the original order the elements were in.

Adamosphere
  • 77
  • 1
  • 2
  • 9

3 Answers3

2

Create all the indices to index into r separately for indices starting with 4 and 5 and then sort them to keep the order of elements as it was originally in r.

So, this should work -

ab = r(sort([4:n:numel(r) 5:n:numel(r)]))
Divakar
  • 218,885
  • 19
  • 262
  • 358
2

A more generic solution for a variable number of starting values:

% example
A = 1:20;

% starting values and number of values to skip
a = [4,5];
n = 5;

% index vector
idx = bsxfun(@plus,a',(0:numel(A)/n-1)*n)

% indexing
result = A(idx(:))

returns:

idx(:)' =  4     5     9    10    14    15    19    20

Another example:

A = 1:40;
a = [3,4,7];
n = 10;
idx = bsxfun(@plus,a',(0:numel(A)/n-1)*n)

returns:

idx(:)' =  3     4     7    13    14    17    23    24    27    33    34    37
Robert Seifert
  • 25,078
  • 11
  • 68
  • 113
1

You can do it using ndgrid (this idea is taken from the code of kron, which does more or less what you want but with products instead of sums):

a = [4 5]; %// initial values
M = 20; %// maximum value
s = 5; %// step

[ii jj] = ndgrid(a,0:s:M-max(a));
ind = (ii(:)+jj(:)).';
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • 1
    I never get the purpose of `.'` instead of just `'` in a lot of your answers. Why are you doing this? – Robert Seifert Mar 20 '14 at 16:59
  • That happens to many people :-) `'` is _conjugate_ transpose, whereas `.'` is standard transpose. When I want to just transpose I use `.'` (even if the arguments are not complex and thus it wouldn't make a difference to conjugate them). Conceptually it's clearer to me not to introduce an unwanted conjugation. Developing the habit of using `'` to transpose [can lead to problems](http://stackoverflow.com/questions/22258444/transfer-function-in-time-domain) – Luis Mendo Mar 20 '14 at 17:05
  • Good to know, though this operator is absolutely misleading in my eyes, as it implies to be used for element-wise complex conjugate transposition. Anyhow, thanks ;) – Robert Seifert Mar 20 '14 at 17:16
  • @thewaywewalk I agree. The dot here is misleading, as it suggests element-wise, which in this case wouldn't make sense – Luis Mendo Mar 20 '14 at 17:17