Reputation: 197
I'd like to see an effective way of estimating the volume of a cone having irregular tapering. We have cone diameters and height in these vectors:
D = c(30, 29, 29, 27) #diameter (cm) vector of the cone
deltah = c(10, 10, 10) #delta height, cm, may vary
Current solution involves a for-loop (in R) using the truncated cone formula for each cone section:
conevol=NULL
for(i in 2:length(D)){
conevol[(i-1)] = (D[i]^2 + D[(i-1)]^2 + D[i]*D[(i-1)]) *deltah[(i-1)]*pi/3
}
sum(conevol)
#[1] 78403.68
So: any idea for a vectorized approach?
Upvotes: 0
Views: 123
Reputation: 2640
No need to use the for loop at all, just create a vector and apply your operation over it:
> D = c(30, 29, 29, 27)
> deltah = c(10, 10, 10)
> i=2:length(D)
> i
[1] 2 3 4
> i-1
[1] 1 2 3
> conevol = (D[i]^2 + D[(i-1)]^2 + D[i]*D[(i-1)]) *deltah[(i-1)]*pi/3
> conevol
[1] 27342.33 26420.79 24640.56
> sum(conevol)
[1] 78403.68
Upvotes: 2