mark g
mark g

Reputation: 11

How to multiply 2d array by a scalar

I'm writing a program to do matrix computations and I need help with a method that will multiply my array by a double number like 2.0. This is what I have so far.

    public Matrix mul(double k) {
        Matrix scaledA = new Matrix(this.rows, this.columns);
        for (int r = 0; r < this.rows; r++) {
            for (int c = 0; c < this.columns; c++) {
                scaledA.data[r][c] = scaledA.data[r][c] * k;
            }
        } 
    return scaledA;
    }   

And this is how I'm trying to call it in main.

    Matrix g = new Matrix(new double[][]{{1, 4},{-2, 3},{0, -1}});
    double k = 2.0;
    Matrix h = g.mul(k);
    System.out.println("h:\n" + h);

I'm able to compile it, but when it prints the entire array that should be scaled is 0.0 Could someone point me in the right direction. I feel like I'm missing something basic, but I can't figure it out.

Upvotes: 1

Views: 406

Answers (1)

f1sh
f1sh

Reputation: 11942

You are using the wrong array as your source for the multiplication:

scaledA.data[r][c] = scaledA.data[r][c] * k;

should be

scaledA.data[r][c] = this.data[r][c] * k;

Upvotes: 1

Related Questions