You are on page 1of 4

Exercise 3

#Matrix row and column subscript begin with 1


y <- matrix(c(1,3,2,4), nrow=2, ncol=2)
y

#internally all elements of a columns are stored together one


#column at a time
y[1]
y[2]
y[3]
y[4]

y[1,]
y[2,]

y[,1]
y[,2]

y[1,1]
y[1,2]
y[2,1]
y[2,2]

#So, R uses a column-major order


y <- matrix(c(1,2,3,4), nrow=2)
y

#but this can be overridden by using byrow=T


m <- matrix(c(1,2,3,4,5,6), nrow=2, byrow=T)
m1 <- matrix(c(1,2,3,4,5,6), nrow=2)
m
m1
#Note: the matrix will still be stored as previously
m[1]
m[2]
m1[1]
m1[2]

#block2: operations
y

y*y
3*y
y+y

#block2b: matrix indexing

z <- matrix(c(1,2,3,4,1,1,0,0,1,0,1,0), nrow=4)


z

z[,2:3]
z[2:3,]

z[c(1,3),]
z[c(1,3),] <- matrix(c(-9,-9,-9,-9,-9,-9), nrow=2)
z
z[c(1,3),] <- c(-1,-1,-1,-1,-1,-1)
z
#block2: filtering

x <- matrix(c(1:3,2:4),nrow=3)
x

x[3,]
x[x[,2]>=3,]
x[c(FALSE, TRUE, TRUE), ]

x[, c(FALSE, TRUE)]

x[c(1:3),]

#block3: functions

z <- matrix(c(1,2,3,4,5,6), nrow=3)


z
str(z)

#apply requires three arguments


#(1) matrix, (2) 1 for rows, 2 for columns, (3) function,
#(4) optional arguments
apply(z,2,mean)
apply(z,1,mean)
apply(z,2,max)

means <- apply(z,2,mean)


means
means[1]
means[2]

#Matrix properties
z <- matrix(1:8, nrow=4)
z
length(z)
dim(z)
nrow(z)
ncol(z)

#Exercise

#(1) Build a matrix 3 x 2 matrix


# Access each row and column
# Compute the mean of each row
# (But the row should contain just odd values)

You might also like