Create a vector with known indices and assign to that values from known vectors
Mostrar comentarios más antiguos
Hello all,
I've got three vectors, with size 1x5
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?
1 comentario
Christina
el 26 de Mayo de 2015
Respuesta aceptada
Más respuestas (3)
Ingrid
el 26 de Mayo de 2015
maybe you can try something like this to keep it vectorized, if in reality your vector only has five elements, than you could also easily use a for loop but I am assuming you are just giving a small test example here
var1Temp = ones(5,1);
var1Temp(positions == 1) = var1(positions == 1);
var2Temp = ones(5,1);
var2Temp(positions == 2) = var2(positions == 2);
var3Temp = ones(5,1);
var3Temp(positions == 3) = var3(positions == 3);
x= var1Temp.*var2Temp.*var3Temp;
1 comentario
Christina
el 26 de Mayo de 2015
Andrei Bobrov
el 26 de Mayo de 2015
var = [ 5 6 7 8 9;11 12 13 14 15;17 18 19 20 21];
pts = [1 1 3 2 2];
[m,n] = size(var);
out = var(sub2ind([m,n],pts,1:n));
1 comentario
Christina
el 26 de Mayo de 2015
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!