本文介绍了用javascript中的矩阵的列(转置)交换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有一个这样的矩阵:

For instance I have a matrix like this:

|1 2 3|
|4 5 6|
|7 8 9|

我需要将其转换为这样的矩阵:

and I need it to convert into a matrix like this:

|1 4 7|
|2 5 8|
|3 6 9|

实现这一目标的最佳方式是什么?

What is the best and optimal way to achieve this goal?

推荐答案

参见文章:在 JavaScript 和 jQuery 中转置数组

function transpose(a) {

  // Calculate the width and height of the Array
  var w = a.length || 0;
  var h = a[0] instanceof Array ? a[0].length : 0;

  // In case it is a zero matrix, no transpose routine needed.
  if(h === 0 || w === 0) { return []; }

  /**
   * @var {Number} i Counter
   * @var {Number} j Counter
   * @var {Array} t Transposed data is stored in this array.
   */
  var i, j, t = [];

  // Loop through every item in the outer array (height)
  for(i=0; i<h; i++) {

    // Insert a new row (array)
    t[i] = [];

    // Loop through every item per item in outer array (width)
    for(j=0; j<w; j++) {

      // Save transposed data.
      t[i][j] = a[j][i];
    }
  }

  return t;
}

console.log(transpose([[1,2,3],[4,5,6],[7,8,9]]));

这篇关于用javascript中的矩阵的列(转置)交换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-31 17:32