views:

64

answers:

3
private void equal_AxB() { 
  int x = matrix_A.length;
  int y = matrix_B[0].length;
  matrix_C = new double[x][y];
   for(int i = 0; i < x; i++) {
            for(int j = 0; j < y; j++) {
              for(int k = 0; k < y; k++){
                matrix_C[i][j] += matrix_A[i][k]*matrix_B[k][j];
          }
        }  
      }

  return;
 }

matrix_A:

2 3
2 3
2 3

matrix_B:

2 3 4
2 4 3
+1  A: 

Two problems I could see:

  • You need to ensure that number of columns of A is equal to number of rows of B. If this does not hold you cannot multiply the matrices.
  • Your k loop should vary from 0 to N where N is number of columns of matrix A, currently you are varying it till number of columns of matrix B.
codaddict
okay, in this statement, we're given that both A and B are compatible right? so any idea on where the problem is?
Samuel
@Samuel: If its given that they are compatible, problem 1 is fixed, you need to fix #2.
codaddict
Alright, how can I fix this? I'm super tired and would like this next fix to be put out tonight..
Samuel
Change `for(int k = 0; k < y; k++){` to `for(int k = 0; k < matrix_A[0].length; k++){` as a quick fix.
codaddict
running a few simple tests now.. thank you very much for your help.. I would also appreciate it if you have and android phone and wouldn't mind.. Check out Ultimath Beta and send me some feedback :) I love feedback but people just use it and don't tell me what they think of it.. thanks again!
Samuel
+1  A: 

You have extracted the first index bound from matrix_A, and the second from matrix_B[0]; you have no guarantee that the remaining bounds relate in any way to those, so the statement:

matrix_C[i][j] += matrix_A[i][k]*matrix_B[k][j];

which accesses all dimensions of A and B may access out of bounds on any of either array's dimensions except A[i], and B[0][j].

Software Monkey
A: 

you have written

int y = matrix_B[0].length;

as you are trying to retrieve the length of sub array of matrix_b

this will return 3 as length, so x and y now have both 3 as value but your matrix_a is 2X3 matrix, which will fails, when you try to find matrix_A at index 2.

try with int y = matrix_B.length;

this will work properly.

Mrityunjay