【算法设计与分析基础】2、矩阵相乘

最近在搞那个activity的事情,算是告一段落了,重新投入学习之中,开始算法与jquery的同步学习,加油!!!

 

package cn.xf.algorithm.ch02;

/**
 * 计算矩阵的乘积
 * @author xiaof
 *
 */
public class Matrix {
	
	/**
	 * 矩阵A,B相乘,获取对应的值
	 * 注意:当矩阵A的列数等于矩阵B的行数时,A与B可以相乘。
	 * @param a
	 * @param b
	 * @return
	 */
	public static Long[][] matrixMultiplication(Long a[][], Long b[][], int aRow, int aColumn, int bRow, int bColumn)
	{
		if(aColumn != bRow)
		{
			return null;
		}
		//结果集是一个A矩阵的行与B矩阵的列的矩阵
		Long result[][] = new Long[aRow][bColumn];
		//首先遍历两个矩阵的相应的行和列
		for(int i = 0; i < aRow; ++i)
		{
			for(int j = 0; j < aColumn; ++j)
			{
				//求对应的行和列相乘之后的所得的积之和
				result[i][j] = 0l;	//首先设置当前值为0
				for(int k = 0; k < bRow; ++k)
				{
					//求积的累加和
					Long count1 = a[i][k];
					Long count2 = b[k][j];
					result[i][j] += a[i][k] * b[k][j];
				}
			}
		}
		
		
		return result;
	}
	
	public static void main(String []args)
	{
		//矩阵a,b
		Long a[][] = new Long[][]{{1l,2l},{3l,4l}};
		Long b[][] = new Long[][]{{1l,2l},{3l,4l}};
		
		Long result[][] = Matrix.matrixMultiplication(a, b, 2, 2, 2, 2);
		for(int i = 0; i < 2; ++i)
		{
			for(int j = 0; j < 2; ++j)
			{
				System.out.print(result[i][j] + "\t");
			}
			System.out.println();
		}
	}
}

  

结果显示:

 

posted @ 2017-03-07 10:45  cutter_point  阅读(301)  评论(0编辑  收藏  举报