matlab - turn arrays into index values

105 views Asked by At

Given a = [1, 7] and b = [4, 10], I want to create a new vector [1:4,7:10]. I can do this with a loop, but I was looking for vectorized solution. I tried using the bsxfun by defining the following function fun = @(c,d) c:d but then using bsxfun(fun, a, b). It generates 1:4 but not 7:10. Thanks.

1

There are 1 answers

0
Divakar On

See if this works for you -

lens = (b - a)+1; %// extents of each group
maxlens = max(lens) %// maximum extent

mask = bsxfun(@le,[1:maxlens]',lens) %// mask of valid numbers
vals = bsxfun(@plus,a,[0:maxlens-1]') %// all values
out = vals(mask).' %// only valid values are collected to form desired output

Sample run -

a =
     1     7    15
b =
     3    12    21
out =
     1   2   3   7   8   9  10  11  12  15  16  17  18  19  20  21