how to replicate an array

前端 未结 4 1646
盖世英雄少女心
盖世英雄少女心 2020-11-30 16:08

I want to make a function like this

>> matdup([1 2],3,4)            %or any other input that user wish to enter
ans= 

 1     2     1     2     1     2         


        
4条回答
  •  时光取名叫无心
    2020-11-30 16:33

    Try kron:

    matdup = @(x,m,n) kron(ones(m,n),x)
    

    Demonstration:

    >> A = [5 6 7];
    >> out = matdup(A,3,2)
    out =
         5     6     7     5     6     7
         5     6     7     5     6     7
         5     6     7     5     6     7
    

    Note that you can switch the inputs to kron to effectively replicate elements rather than the whole matrix:

    repel = @(x,m,n) kron(x,ones(m,n));
    

    Demonstration:

    >> A = [5 6 7];
    >> out = repel(A,3,2)
    out =
         5     5     6     6     7     7
         5     5     6     6     7     7
         5     5     6     6     7     7
    

提交回复
热议问题