Create a vector with known indices and assign to that values from known vectors
古いコメントを表示
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?
採用された回答
その他の回答 (3 件)
Ingrid
2015 年 5 月 26 日
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;
Thorsten
2015 年 5 月 26 日
var = [var1; var2; var3]';
ind = (positions - 1)*size(var, 1) + [1:numel(positions)];
final = var(ind)
Andrei Bobrov
2015 年 5 月 26 日
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));
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!