user2041376
user2041376

Reputation:

vectorize selection of ranges on a 1D vector in Matlab

This is probably very simple, but I can't figure it out... I want to create a matrix of ranges and I can do this using the following loop:

a=[0 10 22 35 42]; % sample initial  ranges
for i=1:length(a)
    b(i,:)= a(i):a(i)+5;
end

 b =
     0     1     2     3     4     5
    10    11    12    13    14    15
    22    23    24    25    26    27
    35    36    37    38    39    40
    42    43    44    45    46    47

How can it be vectorized?

Upvotes: 3

Views: 93

Answers (2)

tmpearce
tmpearce

Reputation: 12693

a = 0:10:40;

b = bsxfun(@plus,a', 0:5)
b =

 0    1    2    3    4    5
10   11   12   13   14   15
20   21   22   23   24   25
30   31   32   33   34   35
40   41   42   43   44   45

Upvotes: 3

gevang
gevang

Reputation: 5014

Both of the following will do for your example:

b = bsxfun(@plus, repmat(a',1,6), 0:5);
b = bsxfun(@plus, a'*ones(1,6), 0:5);

You can modify the arguments according to your input a and range length.

Upvotes: 3

Related Questions