Search code examples
matlabvectorvectorization

Vectorizing the Notion of Colon (:) - values between two vectors in MATLAB


I have two vectors, idx1 and idx2, and I want to obtain the values between them. If idx1 and idx2 were numbers and not vectors, I could do that the following way:

idx1=1;
idx2=5;
values=idx1:idx2 

% Result
 % values =
 % 
 %    1     2     3     4     5

But in my case, idx1 and idx2 are vectors of variable length. For example, for length=2:

idx1=[5,9];
idx2=[9 11];

Can I use the colon operator to directly obtain the values in between? This is, something similar to the following:

values = [5     6     7     8     9     9    10    11]

I know I can do idx1(1):idx2(1) and idx1(2):idx2(2), this is, extract the values for each column separately, so if there is no other solution, I can do this with a for-loop, but maybe Matlab can do this more easily.


Solution

  • Your sample output is not legal. A matrix cannot have rows of different length. What you can do is create a cell array using arrayfun:

    values = arrayfun(@colon, idx1, idx2, 'Uniform', false)
    

    To convert the resulting cell array into a vector, you can use cell2mat:

    values = cell2mat(values);
    

    Alternatively, if all vectors in the resulting cell array have the same length, you can construct an output matrix as follows:

    values = vertcat(values{:});