JavaScript code does not contain a defined Nested Loop

My matrix result has encountered an issue of being undefined. The error message displayed in my chrome console at line 25 is: "Cannot set property "0" of undefined."

After researching similar problems, I've noticed that most solutions for matrix multiplication involve 3 nested loops compared to my 4 nested loops. While the former seems to be more efficient, I find it necessary to use four loops as my iteration spans over two distinct rows and columns. If this difference is causing the bug problem, I would appreciate an explanation on why that is so.

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");
}
}
}        

Answer №1

Modify the line //C[i] = 0; to C[i] = [];. It is necessary to initialize an array under C[i] in order to make use of it later, like 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);

Answer №2

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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for resolving issues with mysql_fetch_assoc()

Similar Question: mysql_fetch_array() error - Fixing parameter issue Whenever I execute the code below, I encounter this issue: Warning: mysql_fetch_assoc(): provided argument is not a valid MySQL result resource If anyone knows how to rectify this pro ...

Showing items in a VueJS component and transferring them to the component

Utilizing VueJS 2.0 and vue-router 2, my goal is to display a template based on route parameters. I have a view called WidgetView where components are dynamically changed. Initially, WidgetComponent is shown which displays a list of widgets. When a user se ...

Customize Vuetify Snackbar timeout function

Can anyone help me with defining a method that will execute after a timeout? Specifically, I would like to trigger a $emit event after a specified timeout, but I am unsure of how to achieve this... <v-snackbar v-model="snackbar" :color="primary" ...

What is the proper way to utilize the decodeURIComponent function?

router.get("/stocks/authed/:symbol", function (req, res, next) { req.db .from("stocks") .select("*") .modify(function(queryBuilder) { if (req.query.from && req.query.to) { queryBuilder.whereBetween('timestamp&apos ...

Tips for turning on a gaming controller before using it

Current Situation In my ionic side menu app, I have a main controller called 'main view'. Each tab in the app has its own controller, which is a child of the main controller. The issue I'm facing is that when I start the app, the first cont ...

An error has occurred: The transport specified is invalid and must be an object containing a log method

Issue: I am facing a problem while trying to run the node server.js file to execute a port listening http_server. It seems like the code is not working properly. Can someone please help me resolve this issue? var socket = require('socket.io'), ...

Replacing an Angular 2 application with a new webpage

I've been working on a project using Angular 2 and following this tutorial: Every time I run my api with npm run api on localhost:3000, the entire application gets replaced by another webpage. https://i.sstatic.net/5pIfX.png Here is my package.json ...

Issue with AngularJS: Dynamically generated tab does not become active or selected

Exploring an AngularJS code snippet that generates tabs upon clicking the new button. However, there's an issue where the newly created tab doesn't become active or selected automatically after creation. It seems like the one before the last tab ...

What is causing my Fabric.js canvas to malfunction?

Here is the link to my JSFiddle project: http://jsfiddle.net/UTf87/ I am facing an issue where the rectangle I intended to display on my canvas is not showing up. Can anyone help me figure out why? HTML: <div id="CanvasContainer"> <canvas id ...

Can dynamic import be beneficial in a node.js environment?

As a newcomer to the world of node.js/express, I must say that I am thoroughly enjoying my experience with it so far. I have adopted ES6 syntax for imports in my project. Initially, when setting up my project, I defined all my routes as follows : app.get ...

Retrieve information from Angular service's HTTP response

Calling all Angular/Javascript aficionados! I need some help with a service that makes API calls to fetch data: app.service("GetDivision", ["$http", function($http){ this.division = function(divisionNumber){ $http.post("/api/division", {division:di ...

How much space should be left from the edge for jQuery UI dialog to be

Typically, a dialog is centered using the following code: $(el).dialog('option', 'position', 'center'); Is there a method to specify a "minimum" distance from the side? For example, ensuring that the top position is always a ...

How to achieve a reverse slideToggle effect with jQuery when refreshing the page

After creating a custom menu on Wordpress using jQuery slideToggle to toggle dropdown on hover, everything seemed to be working perfectly. However, I noticed that when I refreshed the page while moving my cursor between two menu items with dropdown menus, ...

Retrieve the name of the selected checkbox

Currently, I am working on a page where check boxes are generated dynamically. Every time a user clicks on any of the check boxes, the following event is triggered: $(':checkbox').click(function() { }); I would like to know how I can retrieve ...

What is the best way to create a TypeScript interface or type definition for my constant variable?

I'm facing challenges in defining an interface or type for my dataset, and encountering some errors. Here is the incorrect interfaces and code that I'm using: interface IVehicle { [key: number]: { model: string, year: number }; } interface IV ...

Learn how to serialize and submit all form components within a specified element using AJAX

I am attempting to serialize and post all form elements that may originate from either within a <form> element, or any other elements such as divs, trs, etc. In essence, my form can be structured in two ways: <form id="frm1"> Name: ...

Does jqgrid navgrid have an event called "on Refresh"?

Is there a way to trigger an event before the grid automatically refreshes? I am looking for something similar to "onSearch" but for the reset button. Below is the code snippet for the navgrid: $("#jqGrid").jqGrid('navGrid','#jqGridPag ...

What is the best way to change a JSON string into an array of mysterious objects?

I am currently working on a flashcard generator project and I am dealing with a JSON String that is quite complex. The JSON String contains multiple arrays and objects structured like this: data = [{"front":"What is your name?","back":"Billy"},{"front":"H ...

Python Flask login screen not showing error message

Currently, I'm in the process of developing a login screen that incorporates Bootstrap and utilizes jQuery keyframes shaking effect. The backend functionality is managed by Flask. However, I seem to be encountering an issue where the error message "Wr ...

Guide on utilizing getelementsbytagname for retrieving LI values

As I attempt to locate a specific product on amazon.com, my goal is to extract the ASIN for each item. This particular code snippet runs through various search options and retrieves the price of each product from Amazon one by one. However, in addition to ...