矩阵java算法_增量矩阵乘法Java算法实现

题目描述:

增量矩阵是一个元素为初始值initialValue的递增值的矩阵

//  例如,如果初始值initialValue=1,且维度为rows=3 和 columns =3,

//  则增量矩阵为:

//  1  2  3

//  4  5  6

//  7  8  9

//  写一个算法,将原始增量矩阵与其转置阵相乘。

//  输入

//  函数/方法的输入包括三个参数:一个表示初始值的正整数 initialValue,表示增量矩阵中行数的正整数,和表示增量矩阵中列树的正整数。

//  输出

//  返回由增量矩阵和其转置矩阵相乘得到的一个二维矩阵

//  示例

//  输入:

//  initialValue =1   rows = 3   columns = 3

//  输出:

//  14  32  50

//  32  77  122

//  20  122 194

//  解释  对于

//  for  initialValue =1   rows = 3   columns = 3的情况,增量矩阵为

//  1  2  3

//  4  5  6

//  7  8  9

//  其转置矩阵为

//  1  4  7

//  2  5  8

//  3  6  9

//  因此,将由此产生的乘积矩阵为

//  14  32  50

//  32  77  122

//  50  122 194

//  case1: 3 4 2               | case2: 4 3 2

//  25  39   53   67          |

//  39  61   83   105        |  41  59  77

//  53  83   113  143       |  59  85  111

//  67  105  143  181      |  77  111 145

java 核心代码

static void tranposeMultMatrix(int firstValue, int rows, int columns) {

int temp = firstValue;

int newColums = 0;

int newRows = 0;

//处理不是标准矩阵的相乘算法

if (rows > columns) {

newColums = rows;

newRows = rows;

} else if (rows < columns) {

newRows = columns;

newColums = columns;

} else {

newColums = columns;

newRows = rows;

}

int[][] oldArr = new int[newRows][newColums];

int[][] newArr = new int[newRows][newColums];

int[][] result = new int[newRows][newColums];

//存入原来的矩阵数字

for (int i = 0; i < newRows; i++) {

for (int j = 0; j < newColums; j++) {

oldArr[i][j] = temp;

if (i >= rows || j >= columns)

oldArr[i][j] = 0;

else

temp++;

}

}

//存入转化之后的矩阵

temp = firstValue;

for (int i = 0; i < columns; i++) {

for (int j = 0; j < rows; j++) {

newArr[i][j] = temp;

temp += columns;

}

temp = newArr[i][0] + 1;

}

//新旧矩阵相乘

for (int i = 0; i < oldArr.length; i++) {

for (int j = 0; j < oldArr[i].length; j++) {

result[i][j] = 0;

for (int k = 0; k < newArr[i].length; k++) {

result[i][j] += oldArr[i][k] * newArr[k][j];

}

}

}

//输出矩阵

for (int i = 0; i < result.length; i++) {

for (int j = 0; j < result[i].length; j++) {

System.out.print(result[i][j] + " ");

}

System.out.println();

}

}

调用

public static void main(String[] args) {

tranposeMultMatrix(4, 3, 2);

}

经过测试 ,上面的三个用例均无问题。

如有优化或者问题,请及时指出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值