与Matlab中的R rep类似的功能 [英] A similar function to R's rep in Matlab
问题描述
我正在寻找一个功能与Matlab R中的rep
函数类似的函数.例如,使用rep
,我可以执行以下操作:
> 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函数完成了第一部分
>> repmat([1,2,3],1,3)
ans =
1 2 3 1 2 3 1 2 3
但不是第二部分(或者至少我不知道该怎么做).
有什么建议吗?
您可以通过首先定义如下函数来相当接近地重现R中rep函数的语法:
function [result]=rep(array, count)
matrix = repmat(array, count,1);
result = matrix(:);
然后,您可以通过使用行向量或列向量进行调用来重现所需的行为:
>> 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
请注意,我在第二次调用中使用了transpose(')运算符将输入数组作为列向量(3x1矩阵)传递.
我在笔记本电脑上对此进行了基准测试,对于具有100,000个元素重复100次的基本阵列,它比使用上面的ceil选项快2到8倍,具体取决于您要使用第一种还是第二种排列方式. /p>
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
>
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).
Any suggestions?
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
Note I have used the transpose (') operator in the second call to pass the input array as a column vector (a 3x1 matrix).
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 rep类似的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!