0

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?

Dan
  • 45,079
  • 17
  • 88
  • 157
baister
  • 283
  • 2
  • 9
  • 1
    What you want is run-length decoding. Here are some approaches: http://stackoverflow.com/questions/28501418/run-length-decoding-in-matlab – Luis Mendo Apr 12 '16 at 16:34

2 Answers2

4

Since R2015a you can just use the built-in repelem function:

M = repelem(V,L)

or if numel(V) does not equal N

M = repelem(V(1:N),L(1:N))

If you have an older version of MATLAB, consider a simple loop

M = zeros(1, sum(L(1:N)));  %// preallocation
from = 1;
for elem = 1:N
    to = from + L(elem) - 1;
    M(from:to) = v(elem)*ones(1,L(elem));
    from = to + 1;
end
Dan
  • 45,079
  • 17
  • 88
  • 157
2

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
Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52
  • 3
    `v + zeros(1,len)` is going to be faster than `v*ones(1,len)` http://undocumentedmatlab.com/blog/allocation-performance-take-2 – Suever Apr 12 '16 at 14:29