matrix multiplication
I am having difficulty getting my 2 matrices to multiply together to form a 3rd matrix. If anyone can look over my code to see where I went wrong I would be real grateful. I know that it is at the end of the code.
import java.io.*;
public class Matrix {
// Define the main method
public static void main(String arg[]) throws IOException{
//Declare variables and arrays
int x = 0;//initializes how many rows there are in the matrixA
int y = 0;//initializes how many columns there are in the matrixA
int m = 0;//initializes how many rows there are in the matrixB
int n = 0;//initializes how many columns there are in the matrixB
int [][] matrixA = new int [x][y] ;//the completed matrix A
int [][] matrixB = new int [m][n];//the completed matrix B
int [][] matrixC = new int [x][n] ;//the completed matrix C
double [] row = new double [x];// multiplication of matrixC of array
double [] col = new double [y];
//Create a BufferedReader object
BufferedReader in1 = new BufferedReader(
new InputStreamReader(System.in));
//Prompts the user for input values for rows & columns
System.out.println("Please enter the dimensions of the matrix:");
//Prompts the user for input values for rows & columns
System.out.print("Enter number of rows: ");
x = Integer.parseInt(in1.readLine());
System.out.print("Enter number of columns: ");
y = Integer.parseInt(in1.readLine());
System.out.println("The size of the matrix is : " + x + " x " + y);
//performs a loop to gather the coefficients in each row
matrixA = new int [x][y];
//Input numbers into matrix to create the matrix
for (int i = 0; i < x; i++){
for (int j = 0; j < y; j++){
System.out.print("Enter coefficient value a"+ i + j +": ");
matrixA[j]=Integer.parseInt(in1.readLine());
}//Close i loop
System.out.println();
}//Close j loop
for (int i = 0; i < x; i++){
for (int j = 0; j < y; j++){
System.out.print(matrixA[j] + "");
}
System.out.println();
}
BufferedReader in2 = new BufferedReader(
new InputStreamReader(System.in));
//Prompts the user for input values for rows & columns
System.out.println("Please enter the dimensions for matrixB:");
//Prompts the user for input values for rows & columns
System.out.print("Enter number of rows: ");
m = Integer.parseInt(in2.readLine());
System.out.print("Enter number of columns: ");
n = Integer.parseInt(in2.readLine());
System.out.println("The size of the matrix is : " + m + " x " + n);
//performs a loop to gather the coefficients in each row
matrixB = new int [m][n];
//Input numbers into matrix to create the matrix
for (int r = 0; r < m; r++){
for (int s = 0; s < n; s++){
System.out.print("Enter coefficient value b"+ r + s +": ");
matrixB [r][s]=Integer.parseInt(in2.readLine());
}//Close r loop
System.out.println();
}//Close s loop
for (int r = 0; r < m; r++){
for (int s = 0; s < n; s++){
System.out.print(matrixB [r][s] + "");
}
System.out.println();
}
if (x==n)
//performs a loop to gather the coefficients for 3rd matrix
for (int a = 0; a <= x; a++){
for (int b = 0; b <= n; b++){
//Give results
matrixC [x][n] = (matrixC*[s]+[i+1]*[s+1]);
}
}
System.out.println("The results of the new matrix is: " + l + " is: " + row [l]);
}
if ( x > n || x < n)
System.out.println("These two matrices can not be multiplied together:");
return;
}
}
[3870 byte] By [
hawk1968a] at [2007-11-26 21:11:24]

Could you post again using the code tags described here:
http://forum.java.sun.com/help.jspa?sec=formatting
Especially when code contains [i] as an array index, things go horribly wrong
with the formatting.
Does your code compile? If not, post the compiler's messages.
If it does compile and you get unwanted or unexpected behaviour, say what that
behviour is and what you were wanting or expecting - in other words describe
"having difficulty".
The code does not compile but I have eclipse and the problem is in the loop for the 3rd matrix after the "if" statement. I need a code that can make c11 by taking a11b11+a12b21. Here is the code:
import java.io.*;
public class Matrix {
// Define the main method
public static void main(String arg[]) throws IOException{
//Declare variables and arrays
int x = 0;//initializes how many rows there are in the matrixA
int y = 0;//initializes how many columns there are in the matrixA
int m = 0;//initializes how many rows there are in the matrixB
int n = 0;//initializes how many columns there are in the matrixB
int [][] matrixA = new int [x][y] ;//the completed matrix A
int [][] matrixB = new int [m][n];//the completed matrix B
int [][] matrixC = new int [x][n] ;//the completed matrix C
double [] row = new double [x];// multiplication of matrixC of array
double [] col = new double [y];
//Create a BufferedReader object
BufferedReader in1 = new BufferedReader(
new InputStreamReader(System.in));
//Prompts the user for input values for rows & columns
System.out.println("Please enter the dimensions of the matrix:");
//Prompts the user for input values for rows & columns
System.out.print("Enter number of rows: ");
x = Integer.parseInt(in1.readLine());
System.out.print("Enter number of columns: ");
y = Integer.parseInt(in1.readLine());
System.out.println("The size of the matrix is : " + x + " x " + y);
//performs a loop to gather the coefficients in each row
matrixA = new int [x][y];
//Input numbers into matrix to create the matrix
for (int i = 0; i < x; i++){
for (int j = 0; j < y; j++){
System.out.print("Enter coefficient value a"+ i + j +": ");
matrixA [i][j]=Integer.parseInt(in1.readLine());
}//Close i loop
System.out.println();
}//Close j loop
for (int i = 0; i < x; i++){
for (int j = 0; j < y; j++){
System.out.print(matrixA [i][j] + "");
}
System.out.println();
}
BufferedReader in2 = new BufferedReader(
new InputStreamReader(System.in));
//Prompts the user for input values for rows & columns
System.out.println("Please enter the dimensions for matrixB:");
//Prompts the user for input values for rows & columns
System.out.print("Enter number of rows: ");
m = Integer.parseInt(in2.readLine());
System.out.print("Enter number of columns: ");
n = Integer.parseInt(in2.readLine());
System.out.println("The size of the matrix is : " + m + " x " + n);
//performs a loop to gather the coefficients in each row
matrixB = new int [m][n];
//Input numbers into matrix to create the matrix
for (int r = 0; r < m; r++){
for (int s = 0; s < n; s++){
System.out.print("Enter coefficient value b"+ r + s +": ");
matrixB [r][s]=Integer.parseInt(in2.readLine());
}//Close r loop
System.out.println();
}//Close s loop
for (int r = 0; r < m; r++){
for (int s = 0; s < n; s++){
System.out.print(matrixB [r][s] + "");
}
System.out.println();
}
if (x==n)
//performs a loop to gather the coefficients in each row
for (int a = 0; a <= x; a++){
for (int b = 0; b <= n; b++){
//Give results
matrixC [x][n] = (matrixC [i]*[s]+[i+1]*[s+1]);
}}
System.out.println("The results of the new matrix is: " + l + " is: " + row [l]);
}
if ( x > n || x < n)
System.out.println("These two matrices are not compatible to be multiplied together:");
return;
}
}
I should have said that I want to make matrixC by taking "x" of matrixA and "n" of matrixB and multiplying them together like the following example.x11n11+x12+n21
First there's a little typo in that first if-statement near the end: the line should end
with a {.
(The second if-statement would be better expressed as "else".)
You start with matrixA=new int[x][y] having x rows and y columns. And
matrixB=newint[m][n] with m rows and n columns.
You correctly set up the product matrix as having x rows and n columns. But the
condition for the matrices to be "compatible" is that y==m, not x==n.
So the code near the end should be written like:if(y != m) {
System.out.println("These two matrices are not compatible to be multiplied together:");
return;
} else {
// use nested for-loops to
// populate matrixC here
}
Your nested for-loops look OK - I mean the limits of the loops look OK. Well
almost. If there are x rows then the for loop goes from 0 and the test is "less than x"
not "less than or equal to x". In pseudo code (and using nicer variable names) it
should be like:FOR row from 0 to x-1
FOR col from 0 to n-1
SET matrixC[row][col] = 0
// now work along the row
FOR i from 0 to y-1 (which is the same as m-1)
ADD matrixA[row][i] * matrixB[i][col] to matrixC[row][col]
NEXT i
NEXT col
NEXT row
Thankyou for your advice I will give it a whirl.
I am still a little confused on how you enter your code into my program. Could you possibly type what you relayed to me?
What I meant is if you could type the program starting from the if statement I would appreciate it.
int i, j, k;//where a and b are the two matrices to be multiplied and c the resultant
for(i = 0 ; i < m ; i++)// m is the no of rows in first matrix and q no of columsn in second matrix
{
for(j = 0 ; j < q ; j++)
{
c[i][j] = 0;
for(k = 0 ; k < n ; k++)
{
c[i][j] = c[i][j] + (a[i][k]*b[k][j]);
}
}
}
> > int i, j, k;//where a and b are the two matrices
> to be multiplied and c the resultant
> for(i = 0 ; i < m ; i++)// m is the no of rows in
> first matrix and q no of columsn in second matrix
> {
>for(j = 0 ; j < q ; j++)
> {
> c[i][j] = 0;
> for(k = 0 ; k < n ; k++)
> {
>c[i][j] = c[i][j] + (a[i][k]*b[k][j]);
>}
>
> }
>
I am not sure about your code letters. I used x for the row in the first matrix & n for the columns in the 2nd matrix. You used q for one variable and m & n for the other 2 variables. which variables do they represent in my program? Thanks for your help.
hi,
suppose that you have two matrix : A(x, y); B(m, n)
A*B is not possible only if y=m; if so,
A*B = C(x, n);
//Computation of C [j]
for (int k=0; k<y; k++){
C[i] [j] += A[i] [k] * B[k] [j];
}
>
sorry,I meant Computation of C[ i ] [ j ]
Hello again you have been a great help to me. was I correct in doing my if and else statement for this process?
This is what I have done so far with determining matrixC out. Feel free to criticize it and tell me what's wrong with it.
thanks
if (y != m){
System.out.println("These two matrices are not compatible to be multiplied together:");
return;
}
else{
for (int a = 0; a < x; a++){
for (int b = 0; b < n; b++){
matrixC [a][b] = 0;
for (int c = 0; c < n; c++){
matrixC [a][b] = matrixC [a][b] + (matrixA [a][c]*matrixB [c][b]);
}
}
You're missing a couple of trailing }
More importantly the condition of the innermost for-loop is wrong. How many
terms have to be added up to get matrixC[a][b]? They way you have written
it there are n terms, but how many are there really?
[Edit] Maybe a picture will help: y=3 n=4n
+ + +x+ + * +=+ + + +
* * *+ + * ++ + * +
x=2+ + * +x
m=3
The starred entries show the m terms that
must be added to find the product
matrix entry at row 2, column 3
the first part (if, else) is correct. The second is not.
//matrixA(x, y); matrixB(m, n); m=y
for(int i=0; i < x; i++){
for(int j=0; j < y; j++){
C[i] [j] = 0;//initialization
for (int k=0; k < y; k++){
C[i] [j] += A[i] [k] * B[k] [j];
}
}
}
HTH
This entire Matrix class needs quite a bit of OO sprinkled in and (maybe
even more important for now), it needs a couple of simple methods to
get rid of those deeply nested for loops.
Basically multiplying matrixes A*B is repeatedly calculating the dot
product of a matrix row by a column of another matrix. Here it is:private double dot(double[] row, double[][] mat, int col) {
double dot= 0.0;
for (int i= 0; i < row.length; i++)
dot+= row[i]*mat[i][col];
return dot;
}
Assume the dimensions a both A and B are correct for multiplication
and also assume a matrix C has been allocated correctly. The following
method multiplies A and B:double[][] mul(double[][] A, double[][] B, double[][] C) {
for (int r= 0; r < C.length; r++)
for (int c= 0; c < C[0].length; c++)
C[r][c]= dot(A[r], B, c);
return C;
}
kind regards,
Jos
JosAHa at 2007-7-21 18:12:30 >

> the first part (if, else) is correct. The second is
> not.
> //matrixA(x, y); matrixB(m, n); m=y
> > for(int i=0; i < x; i++){
> for(int j=0; j < y; j++){
> C[i] [j] = 0;//initialization
> for (int k=0; k < y; k++){
>C[i] [j] += A[i] [k] * B[k] [j];
>
> }
> }
>
> HTH
where is the n from matrixB in this code, or is it not needed?
> for(int i=0; i < x; i++){
> for(int j=0; j < y; j++){
> C[i] [j] = 0;//initialization
> for (int k=0; k < y; k++){
>C[i] [j] += A[i] [k] * B[k] [j];
> }
> }
> }
This will result in a matrix that is the wrong shape (x by y when it should be x by n).
sorry,for(int j=0; j < n; j++){
Hey that no problem nobody is perfect at 1:30 in the morning. I am getting an out of bounds exception on the code:matricC[i][j] = 0;any ideas why?
before filling the values in the matrixC, you must allocate memory for itmatrixC = new int[ x ] [ n ] ;HTH
> ... > any ideas why?Reply #16?
> any ideas why?You initialised matrixC to be a zero by zero int array near the start (you didn't needto). But, unlike matrixA and matrixB you never later reinitialised to be be thecorrect size.
C = new int[ x ] [ n ];
for(int i=0; i < x; i++){
for(int j=0; j < n; j++){
C[i] [j] = 0;//initialization
for (int k=0; k < y; k++){
C[i] [j] += A[i] [k] * B[k] [j];
}
}
}
Jeez, this thread goes slow ... to be able to multiply matrixes A and B
the number of columns of A must equal the number of rows of B. The
dimensions of the product C equals the number of rows of A by the
number of columns of B. Here's a small method again:double[][] allocateC(double[][] A, double[][] B) {
// incorrect dimensions?
if (A[0].length != B.length) return null;
return new double[A.length][B[0].length];
}
note that C is initialized to all 0.0s by definition.
kind regards,
Jos
JosAHa at 2007-7-21 18:12:30 >

when I input the print code to print out matrixC, do I want to make the code look like this:System.out.print ( matrixC [i][j] + "");
> Jeez, this thread goes slow ... to be able to
> multiply matrixes A and B
> the number of columns of A must equal the number of
> rows of B. The
> dimensions of the product C equals the number of rows
> of A by the
> number of columns of B. Here's a small method
> again:[code]
> double[][] allocateC(double[][] A, double[][] B) {
>// incorrect dimensions?
> if (A[0].length != B.length) return null;
>return new double[A.length][B[0].length];
> code]
> note that C is initialized to all 0.0s by
> definition.
>
> kind regards,
>
> Jos
I appreciate your valuable input but if I were to change now I would have to go back and change everything that I have already done. I do want to thank you again though for your advice, and I will look into that .
for(int i = 0; i < x; i++){
for(int j = 0; j < n; j++){
System.out.print ( matrixC [i][j] + "");
}
System.out.println ();//next row
}
hth
I wanted to thank everybody for there advice. I hope to help someone else with their problems one day.goodnight!
> I appreciate your valuable input but if I were to change now I would
> have to go back and change everything that I have already done.
Change *everything*? I don't understand that; just use the little method
from my reply #25 to setup matrix C and use the mul() and dot() methods
from my reply #19 to do the actual multiplication.
kind regards,
Jos
JosAHa at 2007-7-21 18:12:35 >

int i, j, k;//where a and b are the two matrices to be multiplied and c the resultant
for(i = 0 ; i < firstmatrixrows ; i++)// m is the no of rows in first matrix and q no of columsn in second matrix
{
for(j = 0 ; j < secondmatrixcolumns ; j++)
{
c[i][j] = 0;
for(k = 0 ; k < firstmatrixcloumns ; k++)
{
c[i][j] = c[i][j] + (a[i][k]*b[k][j]);
}
}
}
Other than my reply in #31, what specific question you have since i am seeing this thread grow like the way fragrance from a flower spreads around under the afternoon sun.Quest ( <-- a poet *** philosopher )
> > int i, j, k;//where a and b are the two matrices
> to be multiplied and c the resultant
> for(i = 0 ; i < firstmatrixrows ; i++)// m is the
> no of rows in first matrix and q no of columsn in
> second matrix
> {
>for(j = 0 ; j < secondmatrixcolumns ; j++)
> {
> c[i][j] = 0;
> for(k = 0 ; k < firstmatrixcloumns ; k++)
> {
>c[i][j] = c[i][j] + (a[i][k]*b[k][j]);
>}
>
> }
>
>
>
Apart from from some dubious code, I don't see what this added to the thread that has not already been covered.
1) You use C style declarations for i,j and k when they could be declared in the 'for' loop construction to limit the scope.
2) The variable names do not help the reader work out which is the row, col or sum index.
3) the term c[i][j] = 0 is not needed since c[i][j] will be implicitly zero when the result matrix is constructed
4) The summation term is in my view much better written asc[i][j] += a[i][k]*b[k][j];
5) Names like 'secondmatrixcolumns' violate the Java coding standards. The should be Camal Case names.
6) The comments refer to 'm' and 'q' but 'm' and 'q' don't exist.
7) The comment on the i,j,k declaration has nothing to do with the declaration.
Message was edited by:
sabre150
Message was edited by:
sabre150
@sabre: obviously he is still on his qUeSt!
> Apart from from some dubious code, I don't see what this added to
> the thread that has not already been covered.
Well, the op seems to be happy with one huge method in a class named
Matrix, where different double[][]s are read, allocated, multiplied and
printed; all in the same method. Who are we to complain then,
especially on a sunny Sunday morning ;-)
kind regards,
Jos
JosAHa at 2007-7-21 18:12:35 >

> ...> especially on a sunny Sunday morning ;-)> > kind regards,> > JosWhat sun?
> > especially on a sunny Sunday morning ;-)> > What sun?It certainly is sunny overhere; I checked it again; I know it freezes inFryslan but that area doesn't count :-Pkind regards,Jos ;-)
JosAHa at 2007-7-21 18:12:35 >

> > Apart from from some dubious code, I don't see what
> this added to
> > the thread that has not already been covered.
>
> Well, the op seems to be happy with one huge method
> in a class named
> Matrix, where different double[][]s are read,
> allocated, multiplied and
> printed; all in the same method. Who are we to
> complain then,
But the OP is asking the question and is probably very new to programming and Java in general. He is likely to need guidance as to how best to program and, even if not explicitly stated as the right or wrong way to do things, any code presented should not be as flawed in so many ways as quest's.
> especially on a sunny Sunday morning ;-)
I'm stuck inside sanding the bathroom floor. I have to break every half hour or so so as to clear the dust out of my mouth and throat (yes, I am using a mask and goggles).
A couple more weeks and the grass will require cutting so I will then be allowed outside. Maybe even on my own as long as I can always been seen from the kitchen window!
> It certainly is sunny overhere; I checked it again; I
> know it freezes in Fryslan but that area doesn't count :-P
>
> kind regards,
>
> Jos ;-)
Yeah, yeah.
I used to live in Frysln, I am now living in Rotterdam, studying your westerns technology and, eventually, bringing it back to my home country. Your own technology will then be used agaist you, and we will finally rule over the whole of the Netherlands again, and, and...
; )
> > Well, the op seems to be happy with one huge method [ ... ]
>
> But the OP is asking the question and is probably very new to
> programming and Java in general. He is likely to need guidance as to
> how best to program and, even if not explicitly stated as the right or
> wrong way to do things, any code presented should not be as flawed
> in so many ways as quest's.
I agree here; but when proper coding style is beyond the competence
of the op, it's as if all trash replies are considered valid ;-)
> > especially on a sunny Sunday morning ;-)
>
> I'm stuck inside sanding the bathroom floor. I have to break every half
> hour or so so as to clear the dust out of my mouth and throat (yes, I
> am using a mask and goggles).
I always claim that my religion forbids me from doing those things on
Sundays (as well as on Mondays, Tuesdays etc. etc. ;-)
> A couple more weeks and the grass will require cutting so I will then
> be allowed outside. Maybe even on my own as long as I can always
> been seen from the kitchen window!
Are you allowed a further action radius when you're on a leash? ;-)
kind regards,
Jos (<-- even allowed to be in the back of the barn on my own)
JosAHa at 2007-7-21 18:12:35 >

<snip>
> I agree here; but when proper coding style is beyond
> the competence
> of the op, it's as if all trash replies are
> considered valid ;-)
I always hope that new programmers might learn through osmosis but of course there is no way to create a barrier that is impervious to bad example code.
>
> > especially on a sunny Sunday morning ;-)
>
> I'm stuck inside sanding the bathroom floor. I have
> to break every half
> hour or so so as to clear the dust out of my mouth
> and throat (yes, I
> am using a mask and goggles).
>
> I always claim that my religion forbids me from doing
> those things on
> Sundays (as well as on Mondays, Tuesdays etc. etc.
> ;-)
I have tried several religions in the hope of finding one that will do my DIY for me but no luck. I'm now stuck with the creed 'Except for repairing modern moter cars, do it yourself since you can do it better and cheaper than those professional bodgers'.
<snip>
> Are you allowed a further action radius when you're
> on a leash? ;-)
Of course! What do you think I am?
Sabre (Looking very ghost like in my new dust coating)
> > > > int i, j, k;//where a and b are the two
> matrices
> > to be multiplied and c the resultant
> > for(i = 0 ; i < firstmatrixrows ; i++)// m is
> the
> > no of rows in first matrix and q no of columsn in
> > second matrix
> > {
> >for(j = 0 ; j < secondmatrixcolumns ; j++)
> > {
> > c[i][j] = 0;
> > for(k = 0 ; k < firstmatrixcloumns ; k++)
> > {
> >c[i][j] = c[i][j] + (a[i][k]*b[k][j]);
> >}
> >
> > }
> >
> >
> >
>
> Apart from from some dubious code, I don't see what
> this added to the thread that has not already been
> covered.
*sigh* You did miss his post where he asked me what does m, q and n stand for.