如何将对角线提取为列向量?
假设矩阵M
:
1 2 3
3 5 6
6 8 9
如何存储并从中提取以下行向量a
?
1
5
9
Assume matrix M
:
1 2 3
3 5 6
6 8 9
How do I store I extract the following row vector a
from it?
1
5
9
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需要使用 diag:
请注意,您还可以提取通过将第二个参数传递给 diag 来获得其他对角线,例如
You just need to use diag:
Note that you can also extract other diagonals by passing a second parameter to
diag
, e.g.如果您知道矩阵的尺寸(正方形或其他),您可以提取您喜欢的任何对角线,甚至修改对角线(例如 (1,1)、(2,3)、(3,5) 等中的数字),比使用 diag 更快一些,只需使用如下所示的索引调用:(
注意:这会生成一个行向量;对于列向量,只需转置)对于 NxN 矩阵,只需从所需值开始(顶部为 1 -左角,2表示垂直向下的下一个角,等等),然后递增 N+1,直到达到适当的值。
供参考:
因此,减去 for 循环和 rand 函数的开销,表明使用索引的速度大约是使用 diag 的两倍。我怀疑这纯粹是由于调用 diag 的开销,因为操作本身非常简单且快速,并且几乎可以肯定 diag 本身就是这样工作的。
If you know the dimensions of your matrix (square or otherwise), you can extract any diagonal you like, or even modified diagonals (such as numbers in (1,1), (2,3), (3,5), etc), somewhat faster than using diag, by simply using an index call like this:
(note: this produces a row vector; for a column vector, just transpose) For an NxN matrix, simply start at the desired value (1 for the top-left corner, 2 for next one down vertically, and so on), then increment by N+1 until you reach the appropriate value.
For reference:
So the overhead for the for loop and the rand function, subtracted off, shows that using indices is about twice as fast as using diag. I suspect that this is purely due to the overhead of calling diag, as the operation itself is very straightforward and fast, and is almost certainly how diag itself works.