how to allocate elements of a vector into different rows in a matrix, preserving the column order?

1 view (last 30 days)
Consider
Z = zeros(4,2);
X = [0.15 , 0.33];
P=[2 3];
I am looking for the simplest form of applying P to X and Z so that I obtain:
Z = [0 0; 0.15 0; 0 0.33; 0 0];
The vector P is a vector of indices that applies to the vector X, and positions the column elements of X in the rows of Z indicated in P. So, the number 0.15 moves Down to row 2, (still in column 1) and the number 0.33 moves Down to row 3 (and column 2);
Of course, this is an example. It will apply to much bigger objects.
Thank you.
Joao Ejarque

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 4 Dec 2013
Z = zeros(4,2);
Z(sub2ind(size(Z),P,1:numel(P))) = X;

More Answers (0)

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!