0

I try to make a JavaScript function to show steps of solving a Linear Equation System using the Gauss method. What I got so far (only small part of Gauss elimination method, constructing leading zeros):

let mt = [[2, 3, -1, 5], [4, 0, -3, 3], [-2, 3, -1, 1]];
gaussMethod(mt);

function gaussMethod(mtx) {
    window.GaussMatrixSteps = [];
    window.GaussMatrixSteps[0] = mtx;
    let n = mtx.length;

    for (i = 0; i < n; i++) {
        for (k = i + 1; k < n; k++) {
            var multiplier = mtx[k][i] / mtx[i][i];
            for (j = 0; j <= n; j++) {
                mtx[k][j] = mtx[k][j] - mtx[i][j] * multiplier;
            }
        }
        window.GaussMatrixSteps[i + 1] = mtx;
    }
}

What I get, window.GaussMatrixSteps is an array of same matrices (the last step) instead of different matrices from the different steps. Is it really how JavaScript works?

1 Answer 1

1

Your issue is that you're setting an array to the first element of another array.

let mt = [[2, 3, -1, 5], [4, 0, -3, 3], [-2, 3, -1, 1]];
gaussMethod(mt);

function gaussMethod(mtx) {
    window.GaussMatrixSteps = [];
    window.GaussMatrixSteps[0] = mtx;  // issue is here
    let n = mtx.length;

You're creating this

    [0] = [[2, 3, -1, 5], [4, 0, -3, 3], [-2, 3, -1, 1]]
    [1] = null

What you need to do is remove the reference to the first array or just reuse that array.


You also need to get into the habit of declaring all of your variables using let or const and avoid using the window object as a variable placeholder. So, you can use a private variable inside your function and return it like this:

const GaussMatrixSteps = gaussMethod(mt);

function gaussMethod(mtx) {
    const GaussMatrixSteps = [];
    GaussMatrixSteps[0] = mtx;
    ... CODE HERE
    return GaussMatrixSteps;
}

Also, don't forget to declare the inner for loop variables like this:

    for (let i = 0; i < n; i++) {
        for (let k = i + 1; k < n; k++) {
            for (let j = 0; j <= n; j++) {
            }
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

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.