Matrix Arithmetic and Operations
Perform element-wise and matrix multiplication, addition, and subtraction.
Matrix Arithmetic and Operations is a free R Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, and your progress syncs across the web and the CoddyKit app. The R Academy course includes 4 lessons in total.
Element-wise vs Matrix Operations
R distinguishes between element-wise operations (using +, -, *, /) and true matrix operations (using %*%). Understanding this difference is critical for correct linear algebra.
A <- matrix(c(1,2,3,4), nrow = 2)
B <- matrix(c(5,6,7,8), nrow = 2)
cat('A:
'); print(A)
cat('B:
'); print(B)
# Element-wise multiply
cat('A * B (element-wise):
'); print(A * B)
# Matrix multiply
cat('A %*% B (matrix mult):
'); print(A %*% B)Element-wise Addition and Subtraction
+ and - between two matrices of the same dimensions add or subtract corresponding elements. These are purely element-wise operations.
# Monthly revenue vs target (in thousands)
revenue <- matrix(c(120,135,110,98, 145,160,132,115),
nrow = 2, byrow = TRUE)
target <- matrix(c(130,130,130,130, 150,150,150,150),
nrow = 2, byrow = TRUE)
deviation <- revenue - target
cat('Revenue vs Target deviation:
')
print(deviation)
cat('Above target?:
')
print(revenue >= target)Element-wise Division and Multiplication
Similarly, * and / between matrices of equal size operate element by element. This is useful for scaling, normalising, or combining matrices element-wise.
# Scale a matrix by another (element-wise)
prices <- matrix(c(10, 20, 15, 25), nrow = 2)
quantities <- matrix(c(5, 3, 8, 2), nrow = 2)
total_cost <- prices * quantities
cat('Total cost per item:
')
print(total_cost)
# Normalise to row maximum
max_prices <- matrix(rep(apply(prices, 1, max), 2), nrow = 2)
norm_prices <- prices / max_prices
cat('Normalised prices:
')
print(norm_prices)Scalar Operations on Matrices
You can apply a scalar (single number) operation to every element of a matrix using standard arithmetic operators. The scalar is recycled to match the matrix dimensions.
m <- matrix(c(10, 20, 30, 40, 50, 60), nrow = 2, ncol = 3)
cat('Original:
'); print(m)
cat('m + 5:
'); print(m + 5)
cat('m * 2:
'); print(m * 2)
cat('m / 10:
'); print(m / 10)
cat('m ^ 2:
'); print(m ^ 2)True Matrix Multiplication %*%
A %*% B performs linear algebra matrix multiplication. For this to work, the number of columns in A must equal the number of rows in B. The result has dimensions (rows of A) x (cols of B).
# 2x3 times 3x2 = 2x2
A <- matrix(c(1,2,3, 4,5,6), nrow = 2, byrow = TRUE)
B <- matrix(c(7,8, 9,10, 11,12), nrow = 3, byrow = TRUE)
cat('A (2x3):
'); print(A)
cat('B (3x2):
'); print(B)
cat('A %*% B (2x2):
'); print(A %*% B)rowSums() and colSums()
rowSums(m) computes the sum of each row; colSums(m) computes the sum of each column. Both return named vectors if the matrix has dimension names.
sales <- matrix(
c(120,135,110,98, 145,160,132,115, 88,95,102,78),
nrow = 3, byrow = TRUE,
dimnames = list(c('Q1','Q2','Q3'), c('Jan','Feb','Mar','Apr'))
)
cat('Sales matrix:
'); print(sales)
cat('Quarterly totals:', rowSums(sales), '
')
cat('Monthly totals: ', colSums(sales), '
')rowMeans() and colMeans()
rowMeans(m) and colMeans(m) return the average of each row and column respectively. They are faster than applying mean() with apply() for this common task.
exam_scores <- matrix(
c(88,92,75,81, 79,85,90,73, 95,78,82,88),
nrow = 3, byrow = TRUE,
dimnames = list(c('Alice','Bob','Carol'), c('Math','Sci','Eng','Hist'))
)
cat('Student averages:
')
print(rowMeans(exam_scores))
cat('Subject averages:
')
print(colMeans(exam_scores))Comparison Operations on Matrices
Comparison operators (==, >, <=, etc.) applied to matrices return a logical matrix of the same dimensions. You can then use this mask for subsetting or counting.
scores <- matrix(c(88,45,92,61,73,55,84,79), nrow = 2)
cat('Scores:
'); print(scores)
# Which elements pass?
passing_mask <- scores >= 60
cat('Passing mask:
'); print(passing_mask)
cat('Number passing:', sum(passing_mask), '
')
cat('Passing scores:', scores[passing_mask], '
')apply() for Custom Row/Col Operations
apply(m, MARGIN, FUN) applies a function to rows (MARGIN=1) or columns (MARGIN=2). Use it when you need a custom aggregation beyond rowSums/colMeans.
m <- matrix(c(3,1,4,1,5,9,2,6,5,3,5,8), nrow = 3)
cat('Matrix:
'); print(m)
# Max of each row
cat('Row max: ', apply(m, 1, max), '
')
# Range of each column
cat('Col range:
')
print(apply(m, 2, range))
# Custom: count values > 4 per row
cat('Values > 4 per row:', apply(m, 1, function(x) sum(x > 4)), '
')Broadcasting a Vector Across Rows
When you add or multiply a vector to a matrix, R recycles the vector — cycling through it to match the matrix length. The recycling goes column by column, which can produce unexpected results if you want row-wise operations.
m <- matrix(c(10,20,30, 40,50,60), nrow = 2)
cat('Matrix:
'); print(m)
# Add a 3-element vector: R recycles column-by-column
v <- c(1, 2, 3)
cat('m + c(1,2,3):
'); print(m + v)
# For row-wise scaling, use sweep()
row_weights <- c(0.5, 2.0) # scale row 1 by 0.5, row 2 by 2
cat('Row-wise scaled:
'); print(sweep(m, 1, row_weights, '*'))Arithmetic Operations Summary
Key matrix operation functions in R:
+,-,*,/— element-wise arithmetic%*%— matrix multiplication (linear algebra)rowSums(),colSums()— row/column totalsrowMeans(),colMeans()— row/column averagesapply(m, 1, fn)/apply(m, 2, fn)— custom row/col aggregationsweep()— row/column-wise operations with a vector
m <- matrix(c(4,9,16,25), nrow = 2)
cat('Original:
'); print(m)
cat('sqrt (element-wise):
'); print(sqrt(m))
cat('rowSums:', rowSums(m), '
')
cat('colMeans:', colMeans(m), '
')Quick Check
What does A * B compute when A and B are 2x2 matrices in R?
Recap: Matrix Arithmetic
Great work! Key takeaways from this lesson:
+,-,*,/on matrices are element-wise%*%is true matrix multiplication (rows × columns)rowSums(),colSums(),rowMeans(),colMeans()aggregate over rows/columns- Comparison operators return a logical matrix of the same shape
apply(m, 1, fn)applies a function row-wise;apply(m, 2, fn)column-wise- Use
sweep()for vectorised row/column scaling
# Final: compute grade curve (add 5 to all scores, cap at 100)
raw <- matrix(c(88,55,92,73,60,45,78,95), nrow = 2)
curved <- pmin(raw + 5, 100) # pmin applies min element-wise
cat('Raw:
'); print(raw)
cat('Curved:
'); print(curved)Learn R with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 43
- Lessons
- 159
Frequently Asked Questions
Is the “Matrix Arithmetic and Operations” lesson free?
Yes — any 3 lessons of the R Academy learning path, including “Matrix Arithmetic and Operations”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The R Academy course includes 4 lessons in total.
What will I learn in “Matrix Arithmetic and Operations”?
Perform element-wise and matrix multiplication, addition, and subtraction. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start R Academy?
No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.
How long does the “Matrix Arithmetic and Operations” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this R Academy lesson?
Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Creating Matrices with matrix()
- Matrix Indexing and Subsetting
- Matrix Arithmetic and Operations
- Transposing and Reshaping Matrices