MATLAB: Create a vector with known indices and assign to that values from known vectors

for loopindexingmatrixvectors

Hello all,
I've got three vectors, with size 1×5
var1 = [ 5 6 7 8 9]
var2 = [11 12 13 14 15]
var3 = [17 18 19 20 21]
and I've got another vector with my indices, called positions, where
positions = [1 1 3 2 2]' (size 5 x 1)
*************
At the end I want to create a vector x, which will have the index of the positions column vector, but as we go along and fill in its values, it will get the nth value of the corresponding, var1 or var2 or var3. For example the 1st value of the x vector is corresponding to position 1, so we go to var1 and the 1st value is selected (5). For the last value (5th value) of the x vector, that corresponds to position 2, we go to var2 and the 5th value of var 2 (15) is selected
***************
The final vector x should be in that case x =[ 5 6 19 14 15]
Any ideas?

Best Answer

Try this:
var1 = [ 5 6 7 8 9]
var2 = [11 12 13 14 15]
var3 = [17 18 19 20 21]
positions = [1 1 3 2 2]
numItems = length(positions);
x = zeros(1, numItems);
for k = 1 : numItems
index = positions(k)
if index == 1
x(k) = var1(k);
elseif index == 2
x(k) = var2(k);
else
x(k) = var3(k);
end
end
% Print to command window:
x