Mr.Kinn
Mr.Kinn

Reputation: 409

Find multiple row and column combinations in a matrix in Matlab

I have the following matrix:

>> MatrixA = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
MatrixA =
     1     2     3     4
     5     6     7     8
     9    10    11    12
    13    14    15    16

I want to find the following:

Currently I accomplish this with the following line:

>>diag(MatrixA([1 2 3 4], [2 3 4 4]))
ans =
     2
     7
    12
    16

Is there a more direct way to do this (without using diag)?

Upvotes: 1

Views: 476

Answers (1)

Dan
Dan

Reputation: 45752

Well you could use sub2ind, it might be more intuitive. I don't think there is much benefit though, maybe it's more readable:

ind = sub2ind(size(MatrixA), [1 2 3 4], [2 3 4 4])
MatrixA(ind)

Upvotes: 2

Related Questions