Matlab: repeat every column sequentially n times [duplicate]

喜欢而已 提交于 2019-12-17 07:37:53

问题


I'm pretty much beginner so it's probably possible to do what I want in a simple way. I have a matrix 121x62 but I need to expand it to 121x1488 so every column has to be repeated 24 times. For example, transform this:

   2.2668       2.2667       2.2667       2.2666       2.2666       2.2666       
   2.2582       2.2582       2.2582       2.2582       2.2581       2.2581       
    2.283        2.283        2.283       2.2829       2.2829       2.2829       
   2.2881       2.2881       2.2881       2.2881       2.2881        2.288        
    2.268        2.268       2.2679       2.2679       2.2678       2.2678       
   2.2742       2.2742       2.2741       2.2741       2.2741        2.274    

into this:

2.2668     2.2668     2.2668  and so on to 24th     2.2667     2.2667  and again to 24x
2.2582     2.2582     2.2582 ...

with every column.

I've tried to create a vector with these values and then transform with vec2mat and ok I have 121x1488 matrix but repeated by rows:

2.2668   2.2668   2.2668  2.2668  2.2668  2.2668 ...    2.2582   2.2582  2.2582  2.2582 ...

How to do it by columns?


回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/16266804/matlab-repeat-every-column-sequentially-n-times

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