how to replicate an array

前端 未结 4 1652
盖世英雄少女心
盖世英雄少女心 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:19

    Method 1: Are you allowed to use ones? Try this -

    A = [1 2]
    
    rowIdx = [1 : size(A,1)]';
    colIdx = [1 : size(A,2)]';
    
    out = A(rowIdx(:, ones(3,1)), colIdx(:, ones(4,1)))
    

    Output

    out =
    
         1     2     1     2     1     2     1     2
         1     2     1     2     1     2     1     2
         1     2     1     2     1     2     1     2
    

    Method 2: Are you allowed to use bsxfun and permute? Try this for the same result -

    A = [1 2]
    row_mapped = bsxfun(@plus,A,zeros(3,1))
    out = reshape(bsxfun(@plus,row_mapped,permute(zeros(4,1),[3 2 1])),[3 8])
    

提交回复
热议问题