本文主要是介绍dot production,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
希望下面的是对的
矩阵点乘 dot production
http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=156079&fromuid=109727 扫描短的 然后短的坐标不是0就去看看长的是不是0 有待讨论 表示方法用(index, value) 如果是两个差不多长的 那么就存到哈希表里 然后对于一组元素建立好之后 遍历另一组 然后查询对应的index有没有 如果是一个长一个短 那么就用数组把长的(index, value)建立起来 然后短的每个元素二分查找 如果把一维向量扩展到二维的矩阵 如果要存数组的话 就可以用公式把坐标换成一维的 r,c 变成 r*列数 + c 变回来的话 用i/列数, i%列数 |
package array;import java.util.*;public class DotProduction {public static void main(String[] args){int[] array1 = {0,2,3,0,4,5,0,0};int[] array2 = {2,0,1,0,8,0,0};System.out.println(production1(array1, array2));System.out.println(production2(array1, array2));int[][] m1 = {{0,1,4,5},{0,0,2,0},{4,8,2,0},{1,0,3,1}};int[][] m2 = {{0,0,0,1},{1,0,1,0},{0,0,0,1},{0,0,1,0}};System.out.println(production3(m1, m2));}private static int production1(int[] array1, int[] array2) {if (array1 == null || array1.length == 0 || array2 == null || array2.length == 0) {return 0;}int sum = 0;for (int i = 0; i < array1.length && i < array2.length; i++) {if (array1[i] != 0 && array2[i] != 0) {sum = sum + array1[i]*array2[i];}}return sum;}private static int production2(int[] array1, int[] array2) {if (array1 == null || array1.length == 0 || array2 == null || array2.length == 0) {return 0;}int sum = 0;Map<Integer/*index*/, Integer/*value*/> map1 = new HashMap<>();for (int i = 0; i < array1.length; i++) {if (array1[i] != 0) {map1.put(i, array1[i]);}}for (int i = 0; i < array2.length; i++) {if (array2[i] != 0 && map1.containsKey(i)) {sum = sum + array2[i]*map1.get(i);}}return sum;}//我们假设这是两个n*n的矩阵private static int production3(int[][] matrix1, int[][] matrix2) {if (matrix1 == null || matrix1.length == 0 || matrix2 == null || matrix2.length == 0) {return 0;}int sum = 0;List<Integer/*index*/> l1 = new ArrayList<>();List<Integer/*index*/> l2 = new ArrayList<>();int n = matrix1.length;for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {if (matrix1[i][j] != 0) {l1.add(i*n+j);}}}for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {if (matrix2[i][j] != 0) {l2.add(i*n+j);}}}for (int i: l2) {int start = l1.get(0);int end = l1.get(l1.size() - 1);if (i < start || i > end) {continue;}while (start + 1 < end) {int mid = start + (end - start) / 2;if (mid == i) {int x = mid/n;int y = mid%n;sum = sum + matrix1[x][y] * matrix2[x][y];break;} else if (mid < i) {start = mid;} else {end = mid;}}if (i == start || i == end) {int x = i/n;int y = i%n;sum = sum + matrix1[x][y] * matrix2[x][y];}}return sum;}
}
这篇关于dot production的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!