Adding Two Matrices

From CompSciWiki
Revision as of 11:56, 1 April 2010 by ChristopherJ (Talk | contribs)

Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

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.

 

float
Taken from http://www.flickr.com/photos/daniello/565304023/

An image or By Students section

Solution

class AddMatrices {
public static void main(String args[])
{
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}};
int answer[3][3];
//first loop chooses which row you are in
//also remember that arrays start at index 0
for(int i=0;i<M1.length;i++)
{
for(int j=0;j<M1.length;j++)
{
answer = m1[i][j] + m2[i][j];
} //for j = columns
} //for i = rows
System.out.format("%d %d %d\n",answer[0][0],answer[1][0],answer[2][0]);
System.out.format("%d %d %d\n",answer[0][1],answer[1][1],answer[2][1]);
System.out.format("%d %d %d\n",answer[0][2],answer[1][2],answer[2][2]);
} //main
} //AddMatrices

Code

SolutionCode goes here. Please DO NOT put your code in <pre> tags!

Back to the Program-A-Day homepage