1. Creating Matrix

X = 1:10
M = matrix(X, 1, 10)  # 1x10 matrix (row vector)
M

M = matrix(X, 10, 1)  # 10x1 matrix (column vector)
M

M = matrix(X, 5, 2, byrow=T) # 5x2 matrix
M

M = matrix(runif(30), 10, 3)  # 10x3 matrix with 30 random numbers
M
# Assign column names (optional)
colnames(M) = c("Apple", "Brabo", "Charlie")
M



2. Selecting Rows and Columns

# Selecting Columns
M[, "Brabo"]
M[, 2]

M[, c("Brabo", Charlie)]
M[, c(2, 3)]

# Selecting Rows
M[4, ]
M[3:5, ]
M[c(3, 4, 7), ]


# Selecting Row with conditions
ix = (M[, 1] > .5)  # boolean selector
ix

M[ix, ]

M[(X1[, 1] > .5), ]

sum(ix)
which(ix)

M[which(ix)]



3. Vector and Matrix Multiplication

# Create two vectors
X = matrix(1:3, 1, 3)         # row vector
Y = matrix(c(3, 4, 7), 3, 1)  # column vector

X %*% Y    # vector multiplication

Y %*% X    # vector multiplication


X = matrix(1:9, 3, 3)
Y = matrix(c(4, 3, 5, 1, 2, 4, 7, 6, 4), 3, 3)

Y %*% X    # vector multiplication



# Getting Matrix Inverse
Yinv = solve(Y)
Yinv

Y %*% Yinv    # identity matirx



Code Only

### 1. Creating Matrix
X = 1:10
M = matrix(X, 1, 10)  # 1x10 matrix (row vector)
M

M = matrix(X, 10, 1)  # 10x1 matrix (column vector)
M

M = matrix(X, 5, 2, byrow=T) # 5x2 matrix
M

M = matrix(runif(30), 10, 3)  # 10x3 matrix with 30 random numbers
M
# Assign column names (optional)
colnames(M) = c("Apple", "Brabo", "Charlie")
M


### 2. Selecting Rows and Columns
# Selecting Columns
M[, "Brabo"]
M[, 2]

M[, c("Brabo", Charlie)]
M[, c(2, 3)]

# Selecting Rows
M[4, ]
M[3:5, ]
M[c(3, 4, 7), ]


# Selecting Row with conditions
ix = (M[, 1] > .5)  # boolean selector
ix

M[ix, ]

M[(X1[, 1] > .5), ]

sum(ix)
which(ix)

M[which(ix)]


###3. Vector and Matrix Multiplication
# Create two vectors
X = matrix(1:3, 1, 3)         # row vector
Y = matrix(c(3, 4, 7), 3, 1)  # column vector

X %*% Y    # vector multiplication

Y %*% X    # vector multiplication


X = matrix(1:9, 3, 3)
Y = matrix(c(4, 3, 5, 1, 2, 4, 7, 6, 4), 3, 3)

Y %*% X    # vector multiplication


# Getting Matrix Inverse
Yinv = solve(Y)
Yinv

Y %*% Yinv    # identity matirx