Menu
Coddy logo textTech

Matrix Addition & Substraction

Part of the Logic & Flow section of Coddy's JavaScript journey. Lesson 10 of 65.

To add or subtract two matrices, they must have the same dimensions (i.e., the same number of rows and columns). The operation is performed element-wise, meaning you add or subtract corresponding elements in each matrix.

For example:

Matrix A:
1 2
3 4

Matrix B:
5 6
7 8

A + B:
(1+5) (2+6)
(3+7) (4+8)

Result:
6  8
10 12

Matrix multiplication is more complex and it will be covered in a later section.

challenge icon

Challenge

Easy

Create a function named combineMatrices that takes three arguments: matrixA, matrixB, and a string op which can be either "+" or "-". For each cell, if op is "+", the result should be matrixA[r][c] + matrixB[r][c]. Otherwise, if op is "-", the result should be matrixA[r][c] - matrixB[r][c].

Try it yourself

function combineMatrices(matrixA, matrixB, op) {
  // TODO: For each cell, if op is '+', add the corresponding cells.
  // Otherwise, subtract them. Return the resulting 2D array.
}
// Do not write anything outside function
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 JavaScript compiler