Matlab中的元素数组复制 [英] Element-wise array replication in Matlab

查看:39
本文介绍了Matlab中的元素数组复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个一维数组:<代码>

a = [1, 2, 3];

是否有一个内置的 Matlab 函数,它接受一个数组和一个整数 n 并复制每个数组元素n次?

例如调用 replicate(a, 3) 应该返回 [1,1,1,2,2,2,3,3,3].p>

请注意,这与 repmat 完全不同.我当然可以通过对每个元素执行 repmat 并连接结果来实现 replicate,但我想知道是否有更有效的内置函数.

解决方案

截至 R2015a,有一个 内置和记录的函数来做到这一点,repelem:

<块引用>

repelem 复制数组的元素.
    W = repelem(V,N),用向量V和标量N,创建一个向量W 其中 V 的每个元素重复 N 次.

第二个参数也可以是与V长度相同的向量,用于指定每个元素的复制次数.对于 2D 复制:

B = repelem(A,N1,N2)

不再需要 kron 或其他技巧了!

更新:有关与其他快速方法的性能比较,请参阅问答重复副本数组元素:MATLAB 中的游程解码.

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.

解决方案

As of R2015a, there is a built-in and documented function to do this, repelem:

repelem Replicate elements of an array.
    W = repelem(V,N), with vector V and scalar N, creates a vector W where each element of V is repeated N times.

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:

B = repelem(A,N1,N2)

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.

这篇关于Matlab中的元素数组复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆