Reputation: 115
I have a matrix (x)
x<-c(6,3,2,0,4,8,0,0,5)
x<-matrix(x, nrow = 3, ncol = 3)
[ ,1][ ,2][ ,3]
[1, ] 6 0 0
[2, ] 3 4 0
[3, ] 2 8 5
and a vector (y):
y<-c(0.5,1.2,4.8)
y
[1] 0.5 1.2 4.8
I want to calculate cumulative sum by rows up to matrix diagonal with elements of the vector y. What I need:
[ ,1] [ ,1][ ,2][ ,3] [ ,1]
[1, ] 0.5 [1, ] 6 0 0 [1, ] 3
(y)[2, ] 1.2 * (x) [2, ] 3 4 0 = (w) [2, ] 6,3
[3, ] 4.8 [3, ] 2 8 5 [3, ] 34,6
Where:
[ ,1]
[1, ] 3 0.5*6
(w)[2, ] 6,3 = 0.5*3 + 1.2*4
[3, ] 34,6 0.5*2 + 1.2*8 + 4.8*5
As a result I need this vector (w).
cumsum(y*x)
– calculates all elements of columns in numerical order. I’ve got a vector:
[1] 3.0 6.6 16.2 16.2 21.0 59.4 59.4 59.4 83.4
cumsum(y*t(x))
[1] 3.0 3.0 3.0 4.5 9.3 9.3 10.3 19.9 43.9
I need, that zeros would be not calculated. Is it possible? Thank You in advance!
Upvotes: 1
Views: 256
Reputation: 2709
A for loop can be used to obtain w cumulative values:
w=integer()
for(i in 1:ncol(x)){
w[i]=sum(x[i,1:i]*y[1:i])
}
w
Upvotes: 1