Adding Two Matrices

From CompSciWiki
Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

Add two matrices together using nested loops. Both matrices must be the same size for this problem to work.

You can print the results in any way you would like.

 

...by the Students

When you are taking Matrices and Linear Algebra it is useful to devise programs that do matrices operations for you. It tends to be good practice in both Java and the math course. Devising a program to do matrices multiplication, or finding a dot product will help you further your understanding of both courses.

Solution

To solve this problem you must use nested loops to add two matrices together. If you have not yet taken the course on Matrices and Linear Algebra yet, do not worry. For our purposes we will consider a matrix to simply be a two dimensional array. You may consider the number of columns to be our main array. Our rows will be represented as arrays held within each column. After this has been considered, adding one matrix to the other is simple.

Use these two arrays as the variables in your code, or you may use your own if you wish:

int M1[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
int M2[3][3] = {{9,8,7},{6,5,4},{3,2,1}};

To add one matrix to the other you simply add each corresponding number on the first matrix to the one on the second. For example, I take the number in the first row, and the first column, and add it to the number in the first row and the first column in the second matrix. Once I have done this for each number in both matrices, the resulting matrix will be your answer.

The loops you use should simply iterate through both matrices, add each

Code

Solution Code

Back to the Program-A-Day homepage