简体   繁体   中英

MATLAB: how to pass in the diagonal of a matrix as an argument in another matrix?

Let c be 2D array, and x and y be 1D arrays of the same length (for instance, let's have x=1:7 and y=3:9 ).

I need to find a way to pass in arguments from x and y in the way I will describe below.

If I put simply c(x,y) it will give a 7 by 7 matrix. I don't want that.
Instead, I want to pass in the diagonal of the [xy] matrix: ((x(1), y(1)), (x(2), y(2))...(x(7), y(7)) . Is there a way to do this without a for loop or any iterative statement?

您正在寻找sub2ind函数

res = c( sub2ind(size(c), x, y ) )

There's an easier way. If you're looking for a diagonal, use diag . If you have a matrix c :

c =

    5    8    4    2    9    1    6    1    1
    9    8    7    5    9    3    2    7    5
    2    3    9   10    2    1    4    2    2
    3    2    9    2    4    4    7    2    4
    3    9   10    8    7    5    2    1    8
    5    6    3    7    6    1   10    5    2
    6    1    7    3   10    8    2    4    2

you can find the main diagonal by using diag with no extra arguments:

>> diag(c)
ans =

   5
   8
   9
   2
   7
   1
   2

The second argument, though, indicates which diagonal you want as an offset from the main diagonal. So the default diagonal is equal to 0 . If you want the diagonal starting at c(1,3) , that's 2 above the main diagonal, so

>> diag(c,2)
ans =

   4
   5
   2
   4
   2
   5
   2

Similarly, if you want the diagonal starting at c(4,1) , the offset is -3 :

>> diag(c,-3)
ans =

   3
   9
   3
   3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM