How can I use a vector value as a row index to modify an element?

I have a matrix X (363x8760) with values (real numbers) and another vector V (1x8760) with values (1-363) that indicate a specific row for each column in matrix X. Additionally I have a vector P (1x8760) that contains percentage values (0-1). I need to create a matrix Y (363x8760) equal X expect all values below the row indicated by V are now 0 and the value in the row indicated by V is equal to the original value multiplied by the percentage value.
For example
X = [10 20 50; 30 40 50; 10 20 10]
V = [1 2 3]
P = [.5 .25 .75]
I would want Y to look like
Y = [5 0 0; 30 10 0; 10 20 7.5]

Answers (1)

Y = X;
m = (1:size(X,1))'; % Generic row index vector
g = bsxfun(@lt,m,V); % Logical indexes of the 0's
Y(g) = 0;
g = bsxfun(@eq,m,V); % Logical indexes of the percents
Y(g) = Y(g).*P(:);
Assumes all the values of V are valid row indexes, and the various variable sizes are compatible, etc.

Categories

Asked:

on 8 Dec 2015

Edited:

on 9 Dec 2015

Community Treasure Hunt

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

Start Hunting!