سؤال

Suppose I have a matrix A

A = magic(5)

17    24     1     8    15
23     5     7    14    16
 4     6    13    20    22
10    12    19    21     3
11    18    25     2     9

Now I select a block of this matrix using

A(1:2, 1:2)

17    24
23     5

Now I need the linear index given by (1:2, 1;2) which are (1 2 6 7). Using sub2ind:

sub2ind(size(A),[1:2], [1:2])

But this command returns just (1 7) how can I solve this?

هل كانت مفيدة؟

المحلول

Suppose you want to select A(1:2,2:3):

% Row and column indexes
rind = 1:2;
cind = 2:3;

pos  = bsxfun(@plus,rind', size(A,2)*(cind-1));

pos =
     6    11
     7    12

You might want to reshape it into a column vector pos(:), or in one line with a call to reshape().

نصائح أخرى

You need to specify the 4 subscripts: [1 1], [2 1], [1 2] and [2 2].

>> sub2ind(size(A),[1 2 1 2], [1 1 2 2])

ans =

     1     2     6     7
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top