Difference between revisions of "Adding Two Matrices"

From CompSciWiki
Jump to: navigation, search
Line 1: Line 1:
 
{{1010PrAD|ProblemName=Adding Two Matrices
 
{{1010PrAD|ProblemName=Adding Two Matrices
  
|Problem= Add two matrices together.  Both matrices must be the same size for this problem to work.
+
|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.
 
You can print the results in any way you would like.
|SideSectionTitle=
+
|SideSectionTitle=...by the Students
|SideSection=
+
|SideSection=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.
 
[[Image:OperatingSystemExample.jpg|float|267px]]
 
[[Image:OperatingSystemExample.jpg|float|267px]]
 
<BR>
 
<BR>

Revision as of 12:08, 1 April 2010

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. float
Taken from http://www.flickr.com/photos/daniello/565304023/

An image or By Students section

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.

Code

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

Back to the Program-A-Day homepage