Search code examples
matlabvectorrep

Repeating elements of one vector according to a second


In MATLAB, if N = 2 this is the line I need:

M = [V(1)*ones(1,L(1)) V(2)*ones(1,L(2))];

If N = 3, the line is:

M = [V(1)*ones(1,L(1)) V(2)*ones(1,L(2)) V(3)*ones(1,L(3))];

How could I write a line producing the same results for an arbitrary N?


Solution

  • You can use this:

    M = cell2mat(arrayfun(@(v,len) v*ones(1,len), V, L, 'uni', 0));
    

    example:

    >> V=3:5
    V =
         3     4     5
    >> L=1:3
    L =
         1     2     3
    >> M=cell2mat(arrayfun(@(v,len) v*ones(1,len), V, L, 'uni', 0))
    M =
         3     4     4     5     5     5