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 12Matrix multiplication is more complex and it will be covered in a later section.
Challenge
EasyCreate 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 functionThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate KeysPractice on your own: Online JavaScript compiler