首页 文章

matlab中的Repmat函数

提问于
浏览
0

我在MatLab中遇到过一系列关于Repeat函数的问题,但我无法弄清楚这个过程是如何工作的 .

我试图将其翻译成R,但我的问题是我不知道该函数如何操纵数据 .

代码是制定配对交易策略的过程的一部分,其中代码采用FALSE / TRUE表达式的向量 .

代码是:

% initialize positions array 
positions=NaN(length(tday), 2);

% long entries
positions(shorts, :)=repmat([-1 1], [length(find(shorts)) 1]);

其中short是TRUE / FALSE表达式的向量 .

希望你能帮忙 .

2 回答

  • 3

    repmat重复你给他的矩阵 [dim1 dim2 dim3,...] 次 . 你的代码做的是:

    1.- length(find(shorts)) :在 shorts 中获取"trues"的数量 .

    例如:

    shorts=[1 0 0 0 1 0]
    length(find(shorts))
    ans = 2
    

    2.- repmat([-1 1], [length(find(shorts)) 1]); 重复 [-1 1] [length(find(shorts)) 1] 次 .

    继续例如:

    repmat([-1 1], [length(find(shorts)) 1]);
    ans=[-1 1
         -1 1];
    

    3.- positions(shorts, :)= 将给定的矩阵保存在给定的索引中 . (注意!:仅当 shorts 的类型为 logical 时才有效) .

    继续例如:

    此时,如果您没有省略任何内容,则位置应为 6x2 NaN 矩阵 . 索引将使用 [-1 1] 矩阵填充 shortstrue 位置 . 所以在此之后,职位将是:

    positions=[-1 1
               NaN NaN
               NaN NaN
               NaN NaN
               -1 1
               NaN NaN]
    

    希望能帮助到你

  • 1

    MATLAB repmat函数复制并平铺数组 . 语法是

    B = repmat(A,n)
    

    其中 A 是输入数组, n 指定如何平铺数组 . 如果 n 是向量 [n1,n2] - 在您的情况下 - 则 A 在行中复制 n1 次并在列中复制 n2 次 . 例如 .

    A = [ 1 2 ; 3 4]
    B = repmat(A,[2,3])
    
    B =           |           |
         1     2     1     2     1     2
         3     4     3     4     3     4   __
         1     2     1     2     1     2
         3     4     3     4     3     4
    

    (这些线条仅用于说明 A 如何平铺)

    在您的情况下, repmatshorts 的每个非零元素复制向量 [-1, 1] . 因此,将 shorts 的每一行( shorts 中的相应条目不为零)设置为 [-1,1] . 所有其他行将保持 NaN .

    例如,如果

    shorts = [1; 0; 1; 1; 0];
    

    然后你的代码将创建

    positions = 
              -1    1
              NaN   NaN
              -1    1
              -1    1
              NaN   NaN
    

    我希望这可以帮助你澄清 repmat 的效果 . 如果没有,请随时问 .

相关问题