0

My resultant matrix seems to be undefined. At line 25, this is the error my chrome console gives: "Cannot set property "0" of undefined."

On looking at similar problems, most of the matrix multiplication solutions I've seen use 3 nested loops, as opposed to my 4. Those are probably the better way, but four loops is the only way that makes sense to me, since the iterations are over two separate rows and two separate columns. If this is the cause of my bug issue, could someone please explain why?

const A = [ [-4,0,5], [-3,-1,2], [6,7,-2], [1, 1, 2]],B = [ [1, 0, 3, 0], [4,5,-1, 2], [2, 4, 3, 1]],C = [];
for (var i = 0; i < A.length; i++) {
	//C[i] = 0;
	for (var j = 0; j < A[j].length; j++) {
		//console.log(A[i][j]);
		for (var y = 0; y < B[0].length; y++) {
			C[i][y] = 0;
			for (var x = 0; x < B.length; x++) {
				//console.log(B[x][y]+ "["+x+","+y+"]");
				console.log(C[i][y] + "[" + i + "," + y);
				C[i][y] += A[i][j] * B[x][y];
			}
			console.log(C[i][y] + "[" + i + "," + y + "] is the resultant matrix");
		}
	}
}        

3
  • 1
    And which is line 25? Commented Jul 2, 2019 at 12:56
  • Change //C[i] = 0; to C[i] = []; Commented Jul 2, 2019 at 12:58
  • @mbojko Oh, right, of course! Line 25: C[i][y] += A[i][j] * B[x][y]; Commented Jul 2, 2019 at 13:18

2 Answers 2

1

Change //C[i] = 0; to C[i] = [];. You need to initialize array under C[i] to access it later C[i][y] = 0;

const A = [ [-4,0,5], [-3,-1,2], [6,7,-2], [1, 1, 2]],B = [ [1, 0, 3, 0], [4,5,-1, 2], [2, 4, 3, 1]],C = [];
for (var i = 0; i < A.length; i++) {
	C[i] = [];
	for (var j = 0; j < A[j].length; j++) {

		for (var y = 0; y < B[0].length; y++) {
			C[i][y] = 0;
			for (var x = 0; x < B.length; x++) {
				C[i][y] += A[i][j] * B[x][y];
			}
		}
	}
}
console.log(C);

Sign up to request clarification or add additional context in comments.

2 Comments

Yes! This worked! Thank you so much! -- Can I please further ask how to make my resultant matrix output in a matrix/array form?
@SK your output matrix is in C, so just do console.log(C)
0

const A = [ [-4,0,5], [-3,-1,2], [6,7,-2], [1, 1, 2]],B = [ [1, 0, 3, 0], [4,5,-1, 2], [2, 4, 3, 1]],C = [];
for (var i = 0; i < A.length; i++) {
	C[i] = [];
	for (var j = 0; j < A[j].length; j++) {

		for (var y = 0; y < B[0].length; y++) {
			C[i][y] = 0;
			for (var x = 0; x < B.length; x++) {
				C[i][y] += A[i][j] * B[x][y];
			}
		}
	}
}
console.log(C);

1 Comment

Answered by @ponury-kostek. (Hopefully I did this right; new to Stack.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.