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.
The colon is one of the most useful operators in MATLAB®. It can create vectors, subscript arrays, and specify for iterations. example. x = j : k creates a unit-spaced vector x with elements [j,j+1,j+2,...,j+m] where m = fix(k-j) . If j and k are both integers, then this is simply [j,j+1,...,k] .
The symbol colon ( : ) is used as an operator in MATLAB programming and is a commonly used operator. This operator is used to construct a vector that is defined by a simple expression, iterate over or subscribe to an array, or access a set of elements of an existing vector.
y = linspace( x1,x2 ) returns a row vector of 100 evenly spaced points between x1 and x2 . y = linspace( x1,x2 , n ) generates n points. The spacing between the points is (x2-x1)/(n-1) .
The linspace command The task of creating a vector of equally (or linearly) spaced points between two limits occurs so commonly that MATLAB has a special command linspace to do this. The command linspace(a, b, n) creates n equally spaced points between a and b, including both a and b.
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{:});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With