Sum of two Matrix Numbers

JavaScript

Write a function to print the sum of two matrix numbers:

To write a function that prints the sum of two matrices, you first need to ensure that the matrices have the same dimensions. Then, you can simply add the corresponding elements of each matrix to compute the sum. Here's how you can do it:

js Copy Code
function addMatrices(matrix1, matrix2) {
    const rows = matrix1.length;
    const cols = matrix1[0].length;
    
    // Check if matrices have the same dimensions
    if (rows !== matrix2.length || cols !== matrix2[0].length) {
        return "Matrices must have the same dimensions for addition.";
    }

    const result = [];

    // Iterate over rows
    for (let i = 0; i < rows; i++) {
        const row = [];
        // Iterate over columns
        for (let j = 0; j < cols; j++) {
            // Add corresponding elements from both matrices
            row.push(matrix1[i][j] + matrix2[i][j]);
        }
        // Add row to the result matrix
        result.push(row);
    }

    return result;
}

// Function to print matrix
function printMatrix(matrix) {
    for (let i = 0; i < matrix.length; i++) {
        console.log(matrix[i].join("\t"));
    }
}

// Example usage:
const matrix1 = [[1, 2, 3], [4, 5, 6]];
const matrix2 = [[7, 8, 9], [10, 11, 12]];

const sumMatrix = addMatrices(matrix1, matrix2);

if (typeof sumMatrix === 'string') {
    // Matrices must have the same dimensions for addition.
    console.log(sumMatrix); 
} else {
    printMatrix(sumMatrix);
}
Output:
8	10	12
14	16	18

Explanation:

1. The 'addMatrices' function takes two matrices as input and returns their sum if they have the same dimensions. If the dimensions are not the same, it returns a string indicating that the matrices must have the same dimensions for addition.

2. The 'printMatrix' function prints a matrix by iterating over its rows and columns and joining the elements with tabs ("\t") for formatting.

3. Example usage demonstrates how to use these functions to add two matrices and print the result.

Learn in-depth concepts of matrix systems from the algorithm page.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.