IlPuntoTecnico
Hardware e Software => Programmazione => Topic aperto da: aduri - 12 Ottobre 2006, 15:15
-
Salve a tutti,
mi sto perdendo all'interno dei cicli nidificati per risolvere la moltiplicazione di queste 2 matrici.
Non riesco a inserire l'immagine!!!
comunque la prima matrice va da 1 a 15
la seconda da 1 a 20
il risultato
175 190 205 220
400 440 480 520
625 690 755 820
/*
Moltiplicazione tra 2 matrici 3x5 e 5x4
*/
class Matrici
{
public static void main(String[] args)
{
int a[][]=new int[3][5];
int b[][]=new int[5][4];
int c[][]=new int[3][4];
int i, j, x, y, z;
x=1;
for(i=0; i<3; i=i+1)
{
for(j=0; j<5; j=j+1)
{
a[i][j]=x;
x=x+1;
}
}
y=1;
for(i=0; i<5; i=i+1)
{
for(j=0; j<4; j=j+1)
{
b[i][j]=y;
y=y+1;
}
}
for(z=0; z<3; z=z+1)
{
for(i=0; i<3; i=i+1)
{
for(j=0; j<4; j=j+1)
{
c[i][j]+=a[z][j]*b[j][i];
}
}
}
for(i=0; i<3; i=i+1)
{
for(j=0; j<5; j=j+1)
{
System.out.print(a[i][j]+" ");
}
System.out.println("");
}
System.out.println("");
for(i=0; i<5; i=i+1)
{
for(j=0; j<4; j=j+1)
{
System.out.print(b[i][j]+" ");
}
System.out.println("");
}
System.out.println("");
for(i=0; i<3; i=i+1)
{
for(j=0; j<4; j=j+1)
{
System.out.print(c[i][j]+" ");
}
System.out.println("");
}
}
}
-
questo è il modo corretto
public class esercizio
{
public static void main(String[] argv)
{
int a[][]=new int[3][5];
int b[][]=new int[5][4];
int c[][]=new int[3][4];
int cy = 0;
int cx = 0;
int valore = 0;
int ax = 0;
int ay = 0;
int bx = 0;
int by = 0;
//prima matrice
int num = 1;
for(int i = 0; i < a.length; i++)
{
for(int z = 0; z < a[i].length; z++)
{
a[i][z] = num;
num++;
}
}
//seconda matrice
num = 1;
for(int i = 0; i < b.length; i++)
{
for(int z = 0; z < b[i].length; z++)
{
b[i][z] = num;
num++;
}
}
//calcolo il prodotto
for(int z = 0; z < 3; z++)
{
bx = 0;
cx = 0;
for(int i = 0; i < 4; i++)
{
ax = 0;
by = 0;
valore = 0;
for(int x = 0; x < 5; x++)
{
valore += (a[ay][ax] * b[by][bx]);
ax++;
by++;
}
c[cy][cx] = valore;
cx++;
bx++;
}
cy++;
ay++;
}
// visualizzo il prodotto
for(int y = 0; y < c.length; y++)
{
String riga = "";
for(int x = 0; x < c[0].length; x++)
{
riga += c[y][x]+" ";
}
System.out.println(riga);
}
}
}
-
grazie come sempre