Una forma sencilla y rápida de aprender JAVA, observando y deduciendo cómo se comporta el lenguaje a través de ejemplos prácticos.
Archivo del blog
sábado, 15 de febrero de 2014
Operaciones matemáticas. Multiplicación de un vector por una matriz.
Codigo:
package vectorpormatriz;
public class VectorPorMatriz {
public static void main(String[] args) {
int[] x = new int[3];
int[][] w = new int[3][4];
int[] h = new int[w[0].length];
String aux = "";
//LLenar con valores aleatorios w, h, x.
for (int i = 0; i < w.length; i++) {
x[i] = (int) Math.floor(Math.random() * 89) + 10;
for (int j = 0; j < w[0].length; j++) {
w[i][j] = (int) Math.floor(Math.random() * 89) + 10;
}
}
//Multiplica x por w
for (int i = 0; i < w[0].length; i++) {
int sum = 0;
for (int j = 0; j < x.length; j++) {
sum += x[j] * w[j][i];
}
h[i] = sum;
}
//Mostrar vector
System.out.println("* Vector:");
for (int i = 0; i < x.length; i++) {
aux += " " + x[i];
}
System.out.println(aux);
//Mostrar matriz
System.out.println("\n* Matriz:");
for (int[] m1 : w) {
aux = "";
for (int j = 0; j < w[0].length; j++) {
aux += " " + m1[j];
}
System.out.println(aux);
}
//Mostrar resultado
aux = "";
System.out.println("\n* Vector x Matriz:");
for (int i = 0; i < h.length; i++) {
aux += " " + h[i];
}
System.out.println(aux);
}
}
Resultado:
run:
* Vector:
70 62 39
* Matriz:
34 66 31 59
84 75 27 34
25 54 57 35
* Vector x Matriz:
8563 11376 6067 7603
BUILD SUCCESSFUL (total time: 0 seconds)
Suscribirse a:
Entradas (Atom)
Con la tecnología de Blogger.