如何在 Mathematica 中按第二列对矩阵进行排序?
想象一下您有:
a = {{5, 1, 1}, {2, 0, 7}, {3, -4, 6}}
并且您想按第二列对其进行排序,以获取
b = {{3, -4, 6}, {2, 0, 7}, {5, 1, 1}}
我已尝试使用 SortBy[a, Last]
并适用于最后一列,但我无法让它工作对于第二列。
提前致谢 :-)
Imagine you have:
a = {{5, 1, 1}, {2, 0, 7}, {3, -4, 6}}
and you want to order it by the second column, to get
b = {{3, -4, 6}, {2, 0, 7}, {5, 1, 1}}
I have tried with SortBy[a, Last]
and works for the last column, but I can't get it to work for the second column.
Thanks in advance :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这确实有效:
This does work:
或者,
Alternatively,
在这里,对于强制性计时(我将基本的
Sort
添加到方法中):And here, for the obligatory timing (I added the basic
Sort
to the methods):也许你可以使用这个网址: http://12000.org/my_notes/mma_matlab_control/KERNEL/ node99.htm
您可以使用的代码:
结果:
Maybe you can use this url: http://12000.org/my_notes/mma_matlab_control/KERNEL/node99.htm
Code you can use:
Result:
如果您的数据是:
并且您需要对第二个元素进行稳定排序,则会产生:
尝试使用
SortBy
解决此问题可能会非常令人沮丧,除非您意识到这一点:{ }
括号很重要。If your data were:
And you needed a stable sort on the second element, yielding:
It could be very frustrating to try to solve this with
SortBy
, unless you were aware of this:The
{}
brackets are important.只是在这方面的一个提示:
当使用像
Sqrt[...]
这样的非原子对象时,你可能会得到意想不到的结果:这是由于
当需要数字排序时,始终使用 N。
just a tip in this context:
when using non-atomar objects like
Sqrt[...]
you might get unexpected results:this is due to
Always use N, when a numeric sort is desired.