Javascript中重复的数字序列

时间:2016-06-07 18:10:09

标签: javascript matlab

我想生成由[1 0]组成的100个值的向量: 这就是我在Matlab中做到的:

 n = 100; 
 Seq1 = [1 0]; % sequence of 1-0
 Vector = repmat(Seq1,(n/2),1); % Creates n/2 sequences of 1-0

结果是一个矢量,如:[1 0 1 0 1 0 1 0 ...]

有没有办法用JavaScript获得相同的结果?

3 个答案:

答案 0 :(得分:1)

您可以使用while循环模仿函数repmat

function repmat(array, count) {
    var result = [];
    while (count--) {
        result = result.concat(array);
    }
    return result;
}

var nTrials = 100,
    Seq1 = [1, 0],
    Vector = repmat(Seq1, nTrials / 2); 

console.log(Vector);

答案 1 :(得分:0)

假设您正在寻找添加1然后添加0的方法,而不是包含1和0的数组:

var myArray = [];
nTrials = 30;
for(i = 1; i<= nTrials/2; i++){
  myArray.push(1);
  myArray.push(0)
}
document.body.innerHTML = myArray[1];}

https://jsfiddle.net/6seqs6af/1/

答案 2 :(得分:0)

FWIW,这是JavaScript中的完整repmat实现。

它使用箭头功能(=>),并非在所有浏览器中都可用。

&#13;
&#13;
 // Seq1 is an Array (1D vector). We need a Matrix which JavaScript doesn't have
 // natively. But we can derive a Matrix type from an Array by adding 
 // `numberOfRows` and `numberOfColumns` properties as well as a `set` method 

 function Matrix(numberOfRows, numberOfColumns) {
   this.numberOfColumns = numberOfColumns;
   this.numberOfRows = numberOfRows;
   this.length = numberOfColumns * numberOfRows;
   this.fill();
 }

 Matrix.prototype = Array.prototype;

 Matrix.prototype.set = function() {
   for (var i = 0; i < arguments.length; i++) {
     this[i] = arguments[i];
   }
   return this;
 }

 Matrix.prototype.toString = function() {
   return this.reduce((acc, x, idx) => acc + (idx % this.numberOfColumns === this.numberOfColumns - 1 ? x + '\n' : x + ', '), '');
 }

 Matrix.prototype.at = function(row, column) {
   return this[row * this.numberOfColumns + column];
 }

 // Repmap
 // ======

 function repmat(mat, repeatColumns, repeatRows) {
   var numberOfColumns = mat.numberOfColumns * repeatColumns;
   var numberOfRows = mat.numberOfRows * repeatRows;

   var values = [];
   for (var y = 0; y < numberOfRows; y++) {
     for (var x = 0; x < numberOfColumns; x++) {
       values.push(mat.at(y % mat.numberOfRows, x % mat.numberOfColumns));
     }
   }

   var result = new Matrix(numberOfRows, numberOfColumns);
   result.set.apply(result, values);

   return result;
 }

 // Calculation
 // ===========

 var nTrials = 100;

 var seq1 = new Matrix(1, 2);
 seq1.set(1, 0);

 var vector = repmat(seq1, nTrials / 2, 1);

 console.log(vector.toString());
&#13;
&#13;
&#13;