MATLAB索引问题
例如,我有一个矩阵
A = [ 1 2 3; 4 5 6; 7 8 9] ;
和一个大小为 1x3 的向量,它指定每行中的哪个元素是我要查找的元素 - 即如果
vector = [ 1 2 1 ]
那么所需的输出是
[ 1 5 7 ]
因为 1
是第一个第 1 行中的元素,5
是第 2 行中的第 2 个元素,7
是第 3 行中的第 1 个元素。
我该如何实现这一目标?找不到内置函数来执行此操作,这让我感到惊讶。
I have a matrix, for example
A = [ 1 2 3; 4 5 6; 7 8 9] ;
and a vector of size 1x3 which specifies which element in each row is the one I'm looking for - i.e. If
vector = [ 1 2 1 ]
then the desired output is
[ 1 5 7 ]
since 1
is the 1'st element in the 1'st row, 5
is the 2'nd in the 2'nd row, and 7
is the 1'st element in the 3'rd row.
How do I achieve this? Couldn't find a built in function to do this, which surprised me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
MATLAB 提供 SUB2IND 函数将行/列下标转换为线性索引:
MATLAB provides the SUB2IND function to convert rows/columns subscripts to linear indices:
首先,Matlab中的索引是从上到下的。
所以在你的情况下 A[1] = 1 , A[2] = 4 , A[3] = 7
这就是说,处理 A' 会更容易,因为它有点微不足道。
First of all, the indexes in Matlab go from top to bottom.
So in your case A[1] = 1 , A[2] = 4 , A[3] = 7
That said, it would be easier to work on A' , because its a bit more trivial.
这有点难看,但是
diag(A(1:3,[1 2 1]))
可以解决问题。It's a bit ugly, but
diag(A(1:3,[1 2 1]))
will do the trick.这是 Yochai 的答案的变体,但没有转置(这基本上也是SUB2IND 在 Amro 的回答):
或者对于任意大小的数组
A
:Here's a variation of Yochai's answer but without the transpose (this is also basically what SUB2IND does in Amro's answer):
Or for an array
A
of an arbitrary size: