简体   繁体   中英

Matrix algebra in R

I have: x= 1 x 999 vector of Brownian motion y= 1 x 999 vector of Brownian motion (I can simulate these pretty easily)

I want to set up a 1000x1000 matrix called z as follows: - First row and column will be full of zeroes - Every other element will be the product elementwise of x and y ie the 2nd row of the second column of z would be x[1]*y[1] etc until the 1000th row of the 1000th column will be x[999]*y[999] (and to take another example the 3rd row of the 4th column would be x[3]*y[4]

How would I go about doing this?

You're looking for outer :

x <- 1:3
y <- 2:4
cbind(0, rbind(0, outer(x, y)))
#      [,1] [,2] [,3] [,4]
# [1,]    0    0    0    0
# [2,]    0    2    3    4
# [3,]    0    4    6    8
# [4,]    0    6    9   12

If you wanted to plot z for every pair of x and y values, you might find it more convenient to plot using

to.plot <- expand.grid(x=c(0, x), y=c(0, y))
to.plot$z = to.plot$x * to.plot$y
to.plot
#    x y  z
# 1  0 0  0
# 2  1 0  0
# 3  2 0  0
# 4  3 0  0
# 5  0 2  0
# 6  1 2  2
# 7  2 2  4
# 8  3 2  6
# 9  0 3  0
# 10 1 3  3
# 11 2 3  6
# 12 3 3  9
# 13 0 4  0
# 14 1 4  4
# 15 2 4  8
# 16 3 4 12

Then you could plot with something like:

library(scatterplot3d)
scatterplot3d(to.plot$x, to.plot$y, to.plot$z)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM