与 Matlab 中 R 的代表类似的功能 [英] A similar function to R's rep in Matlab
问题描述
我正在寻找一个与 R 中的 rep
函数类似的函数,用于 Matlab.例如,使用 rep
我可以执行以下操作:
I am looking for a function that behaves similarly to the rep
function in R for Matlab. For example with rep
I can do the following:
> rep(c(1,2,3),times=3)
[1] 1 2 3 1 2 3 1 2 3
> rep(c(1,2,3),each=3)
[1] 1 1 1 2 2 2 3 3 3
>
在matlab中有repmat函数完成第一部分
In matlab there is the repmat function which accomplishes the first part
>> repmat([1,2,3],1,3)
ans =
1 2 3 1 2 3 1 2 3
但不是第二部分(或者至少我不知道该怎么做).
but not the second part (or at least I can't figure out how to do it).
有什么建议吗?
推荐答案
您可以通过首先定义如下函数来相当接近地重现 R 中 rep 函数的语法:
You can reproduce the syntax of the rep function in R fairly closely by first defining a function as follows:
function [result]=rep(array, count)
matrix = repmat(array, count,1);
result = matrix(:);
然后您可以通过使用行或列向量调用来重现所需的行为:
Then you can reproduce the desired behavior by calling with either a row or column vector:
>> rep([1 2 3],3)
ans =
1 1 1 2 2 2 3 3 3
>> rep([1 2 3]',3)
ans =
1 2 3 1 2 3 1 2 3
请注意,我在第二次调用中使用了转置 (') 运算符将输入数组作为列向量(3x1 矩阵)传递.
Note I have used the transpose (') operator in the second call to pass the input array as a column vector (a 3x1 matrix).
我在我的笔记本电脑上对此进行了基准测试,对于一个包含 100,000 个元素重复 100 次的基本数组,它比使用上面的 ceil 选项快 2 到 8 倍,具体取决于您想要第一种还是第二种排列.
I benchmarked this on my laptop, and for a base array with 100,000 elements repeated 100 times, it was between 2 to 8 times faster than using the ceil option above, depending on whether you want the first or the second arrangement.
这篇关于与 Matlab 中 R 的代表类似的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!