如何在矩阵前添加一列?
好吧,假设我有这个矩阵:{{1,2},{2,3}},我宁愿有 {{4,1,2},{5,2,3}}。 也就是说,我在矩阵前面添加了一列。 有简单的方法吗?
我最好的建议是:
PrependColumn[vector_List, matrix_List] :=
Outer[Prepend[#1, #2] &, matrix, vector, 1]
但它混淆了代码,并且不断需要加载越来越多的代码。 这不是以某种方式内置的吗?
Ok, imagine I have this Matrix: {{1,2},{2,3}}, and I'd rather have {{4,1,2},{5,2,3}}. That is, I prepended a column to the matrix. Is there an easy way to do it?
My best proposal is this:
PrependColumn[vector_List, matrix_List] :=
Outer[Prepend[#1, #2] &, matrix, vector, 1]
But it obfuscates the code and constantly requires loading more and more code. Isn't this built in somehow?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为最不晦涩的是执行此操作的以下方法是:
通常,
MapThread
是您在执行此类任务时最常使用的函数(我在添加标签时一直使用它)到数组,然后使用Grid
很好地格式化它们),并且使用Prepend
而不是等效的Prepend[#1, #2]&
。I think the least obscure is the following way of doing this is:
In general,
MapThread
is the function that you'll use most often for tasks like this one (I use it all the time when adding labels to arrays before formating them nicely withGrid
), and it can make things a lot clearer and more concise to usePrepend
instead of the equivalentPrepend[#1, #2]&
.由于 Mathematica 6 中引入了 ArrayFlatten ,因此最不混淆的解决方案必须是
一个很好的技巧,即用 0 替换任何矩阵块可以为您提供正确大小的零块。
Since
ArrayFlatten
was introduced in Mathematica 6 the least obfuscated solution must beA nice trick is that replacing any matrix block with
0
gives you a zero block of the right size.我认为最常见的方法是转置、前置、再次转置:
I believe the most common way is to transpose, prepend, and transpose again:
...绝对..到目前为止...从我对数组
RandomReal[100,{10^8,5}]
上的各种方法的测试中追加或添加列的最快方法(孩子们,不要在家尝试这个...如果您的机器不是为了速度和内存而构建的,那么在这种大小的阵列上进行操作肯定会挂起您的计算机)...是这样的:
Append[tmp\[Transpose], Range@Length@tmp]\[Transpose]
。随意将
Append
替换为Prepend
。第二快的事情是:
Table[tmp[[n]]~Join~{n}, {n, Length@tmp}]
- 几乎慢两倍。THE... ABSOLUTELY.. BY FAR... FASTEST method to append or prepend a column from my tests of various methods on array
RandomReal[100,{10^8,5}]
(kids, don't try this at home... if your machine isn't built for speed and memory, operations on an array this size are guaranteed to hang your computer)...is this:
Append[tmp\[Transpose], Range@Length@tmp]\[Transpose]
.Replace
Append
withPrepend
at will.The next fastest thing is this:
Table[tmp[[n]]~Join~{n}, {n, Length@tmp}]
- almost twice as slow.