Matrix-Multiplikation

Da ist keine Umwandlung drin..

Java:
import java.math.BigDecimal;

public class MatrixMultiplication3x3 {

    public static double[][] mult3x3(double[][] A, double[][] B) {

        if (A.length != B.length || A[0].length != B[0].length) {
            System.out.println("ERROR: Check your dimension! \n");
            return new double[0][0];
        }

        double[][] C = new double[A.length][A[0].length];

        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j < B[0].length; j++) {
                C[i][j] = 0;
                for (int k = 0; k < A[0].length; k++) {
                 C[i][j] += A[i][k] * B[k][j];
                }
            }
        }
        return C;
    }
    public static double round(double value, int scale) {
        if (scale < 0) throw new ArithmeticException("scale is negative");
        BigDecimal d = new BigDecimal(Double.toString(value));
        return d.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    public static void draw(double[][] M) {
        for (int i = 0; i < M.length; i++)
            for (int j = 0; j < M[0].length; j++)
                System.out.print((j == 0 ? "|" : "") + M[i][j]
                        + (j == M[0].length - 1 ? "|\n" : "\t"));
        System.out.println();
    }

    public static void main(String args[]) {

        double[][] A = { { 0.0, -1.0, 0.0}, { 1.0, 0.0, 0.0},
                { 0.0, 0.0, 1.0}};
     
        double[][] B = { { 0.0, 1.0, 0.0}, { -1.0, 0.0, 0.0},
                { 0.0, 0.0, 1.0}};

        double[][] C = mult3x3(A, B);

        draw(A);
        System.out.println("*\n");
        draw(B);
        System.out.println("=\n");
        draw(C);

    }

}

Ausgabe:
Code:
|0.0    -1.0    0.0|
|1.0    0.0    0.0|
|0.0    0.0    1.0|

*

|0.0    1.0    0.0|
|-1.0    0.0    0.0|
|0.0    0.0    1.0|

=

|1.0    0.0    0.0|
|0.0    1.0    0.0|
|0.0    0.0    1.0|

Du hast den Code oben jetzt ja noch im Nachhinein verändert aber nicht zum besseren...

du greifst auf ein 2-Dimensionales Array auf 3-Dimensionen zu:
Java:
        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j < B[0].length; j++) {
                C[i][I][j] = 0; //<---- 3-Dimensionen
                for (int k = 0; k < A[0].length; k++) {
                    C[i][I][j] += A[i][I][k] * B[k][j];
                    return C;
                }
            }
        }
    }


Du schreibst den Index i beim Zugriff groß (ebenso in der Draw-Methode)
Hast du mal den Code von mir ausprobiert?

Viele Grüße
Youza
 

Neue Beiträge

Zurück