Menu
Coddy logo textTech

Matrix Arithmetic

Part of the Logic & Flow section of Coddy's R journey. Lesson 20 of 64.

Arithmetic between a matrix and a number, or between two matrices of the same size, works cell by cell:

a <- matrix(1:4, nrow = 2, byrow = TRUE)
b <- matrix(c(10, 20, 30, 40), nrow = 2, byrow = TRUE)
print(a * 2)
print(a + b)

Output:

     [,1] [,2]
[1,]    2    4
[2,]    6    8
     [,1] [,2]
[1,]   11   22
[2,]   33   44

A comparison also works cell by cell and returns a logical matrix. Use it to count cells, or as an index to change only the matching cells:

m <- matrix(c(4, 12, 7, 15), nrow = 2, byrow = TRUE)
print(sum(m > 10))
m[m > 10] <- 10
print(m)

Output:

[1] 2
     [,1] [,2]
[1,]    4   10
[2,]    7   10

t(m) swaps rows and columns. %*% is the matrix product, where each result cell combines a row of the first matrix with a column of the second, so ncol(a) must equal nrow(b):

a <- matrix(1:4, nrow = 2, byrow = TRUE)
print(t(a))
print(a %*% a)

Output:

     [,1] [,2]
[1,]    1    3
[2,]    2    4
     [,1] [,2]
[1,]    7   10
[2,]   15   22

Cell-by-cell arithmetic between matrices of different sizes stops with the error non-conformable arrays, so compare dim() first. The matrix product has its own size rule:

a <- matrix(1:4, nrow = 2)
b <- matrix(1:6, nrow = 2)
print(identical(dim(a), dim(b)))
print(dim(a %*% b))

Output:

[1] FALSE
[1] 2 3
challenge icon

Challenge

Easy

Complete cap_values(m, limit). Return two lines: Over: with the number of cells above limit, then Total: with the sum of the matrix after every value above limit is replaced by limit.

The supplied code reads a matrix from one line: rows are separated by ; and the values of a row by ,, so 1,2;3,4 is a matrix with the rows 1 2 and 3 4. The next line holds limit. The code prints each returned line.

Try it yourself

cap_values <- function(m, limit) {
  # Write your code here
  c("Over: 0", "Total: 0")
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
parse_matrix <- function(line) {
  rows <- strsplit(line, ";")[[1]]
  matrix(as.numeric(unlist(strsplit(rows, ","))), nrow = length(rows), byrow = TRUE)
}
cat(cap_values(parse_matrix(input[1]), as.numeric(input[2])), sep = "\n")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler