Matlab 中的逐元素数组复制
假设我有一个一维数组: <代码>
a = [1, 2, 3];
是否有一个内置的 Matlab 函数,它接受一个数组和一个整数 n 并复制每个 数组元素n次?
例如,调用 replicate(a, 3)
应返回 [1,1,1,2,2,2,3,3,3]
。
请注意,这与 repmat
完全不同。我当然可以通过对每个元素执行 repmat
并连接结果来实现 replicate
,但我想知道是否有一个更高效的内置函数。
Let's say I have a one-dimensional array:
a = [1, 2, 3];
Is there a built-in Matlab function that takes an array and an integer n
and replicates each
element of the array n times?
For example calling replicate(a, 3)
should return [1,1,1,2,2,2,3,3,3]
.
Note that this is not at all the same as repmat
. I can certainly implement replicate
by doing repmat
on each element and concatenating the result, but I am wondering if there is a built in function that is more efficient.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我是 KRON 函数的粉丝:
您还可以查看 此相关问题(涉及复制二维矩阵的元素)以查看涉及矩阵索引的其他一些解决方案。这是一个这样的解决方案(灵感来自 Edric 的回答):
I'm a fan of the KRON function:
You can also look at this related question (which dealt with replicating elements of 2-D matrices) to see some of the other solutions involving matrix indexing. Here's one such solution (inspired by Edric's answer):
从 R2015a 开始,有一个内置和记录了执行此操作的函数,
repelem
:第二个参数也可以是与 V 长度相同的向量,以指定每个元素的复制次数。对于 2D 复制:
不再需要
kron
或其他技巧!更新:要与其他快速方法进行性能比较,请参阅问答重复数组元素的副本: MATLAB 中的游程解码。
As of R2015a, there is a built-in and documented function to do this,
repelem
:The second argument can also be a vector of the same length as
V
to specify the number of replications for each element. For 2D replication:No need for
kron
or other tricks anymore!UPDATE: For a performance comparison with other speedy methods, please see the Q&A Repeat copies of array elements: Run-length decoding in MATLAB.
一些奇异的替代品。诚然,有趣多于有用:
将
meshgrid
的(第一个)结果分配给向量:构建一个矩阵,乘以
a
得到结果:使用
ind2sub
生成索引:Some exotic alternatives. Admittedly more funny than useful:
Assign the (first) result of
meshgrid
to a vector:Build a matrix that multiplied by
a
gives the result:Use
ind2sub
to generate the indices:如果您有图像处理工具箱,还有另一种选择:
If you have the image processing toolbox, there is another alternative: