如何将对角线提取为列向量?

发布于 2024-12-17 09:14:52 字数 140 浏览 0 评论 0原文

假设矩阵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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

终陌 2024-12-24 09:14:52

您只需要使用 diag

octave-3.4.0:1> A = [ 1 2 3; 3 5 6; 6 8 9 ]
A =

   1   2   3
   3   5   6
   6   8   9

octave-3.4.0:2> D = diag(A)
D =

   1
   5
   9

请注意,您还可以提取通过将第二个参数传递给 diag 来获得其他对角线,例如

octave-3.4.0:3> D = diag(A, 1)
D =

   2
   6

octave-3.4.0:4> D = diag(A, -1)
D =

   3
   8

You just need to use diag:

octave-3.4.0:1> A = [ 1 2 3; 3 5 6; 6 8 9 ]
A =

   1   2   3
   3   5   6
   6   8   9

octave-3.4.0:2> D = diag(A)
D =

   1
   5
   9

Note that you can also extract other diagonals by passing a second parameter to diag, e.g.

octave-3.4.0:3> D = diag(A, 1)
D =

   2
   6

octave-3.4.0:4> D = diag(A, -1)
D =

   3
   8
帥小哥 2024-12-24 09:14:52

如果您知道矩阵的尺寸(正方形或其他),您可以提取您喜欢的任何对角线,甚至修改对角线(例如 (1,1)、(2,3)、(3,5) 等中的数字),比使用 diag 更快一些,只需使用如下所示的索引调用:(

a=M(1:4:9)

注意:这会生成一个行向量;对于列向量,只需转置)对于 NxN 矩阵,只需从所需值开始(顶部为 1 -左角,2表示垂直向下的下一个角,等等),然后递增 N+1,直到达到适当的值。

octave:35> tic; for i=1:10000 diag(rand(3)); end; toc;
Elapsed time is 0.13973 seconds.
octave:36> tic; for i=1:10000 rand(3)(1:4:9); end; toc;
Elapsed time is 0.10966 seconds.

供参考:

octave:49> tic; for i=1:10000 rand(3); end; toc;
Elapsed time is 0.082429 seconds.
octave:107> version
ans = 3.6.3

因此,减去 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:

a=M(1:4:9)

(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.

octave:35> tic; for i=1:10000 diag(rand(3)); end; toc;
Elapsed time is 0.13973 seconds.
octave:36> tic; for i=1:10000 rand(3)(1:4:9); end; toc;
Elapsed time is 0.10966 seconds.

For reference:

octave:49> tic; for i=1:10000 rand(3); end; toc;
Elapsed time is 0.082429 seconds.
octave:107> version
ans = 3.6.3

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文