Matlab: repeat every column sequentially n times [duplicate]

老子叫甜甜 提交于 2019-11-27 05:10:28

Suppose you have this simplified input and you want to expand columns sequentially n times:

A   = [1 4
       2 5
       3 6];

szA = size(A); 
n = 3;

There are few ways to do that:

  • Replicate, then reshape:

    reshape(repmat(A,n,1),szA(1),n*szA(2))
    
  • Kronecker product:

    kron(A,ones(1,n))
    
  • Using FEX: expand():

    expand(A,[1 n])
    
  • Since R2015a, repelem():

    repelem(A,1,n)
    

All yield the same result:

ans =
     1     1     1     4     4     4
     2     2     2     5     5     5
     3     3     3     6     6     6

Just for the sake of completeness. If you want to duplicate along the rows, you can also use rectpulse().

A = [1,2,3;...
     4,5,6];

n = 3;

rectpulse(A, n);

gives you

1  2  3
1  2  3
1  2  3
4  5  6
4  5  6
4  5  6

Here You go:

function [result] = repcolumn(A, n)
    %n - how many times each column from A should be repeated

    [rows columns] = size(A);
    result = repmat(A(:,1),1,n);

    for i = 2:columns
        result = [result,repmat(A(:,i),1,n)];
    end
end

There must be an easier way but it does the job.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!