简体   繁体   English

Javascript中重复的数字序列

[英]Repeated sequence of numbers in Javascript

I want to generate a vector of 100 values composed by [1 0]: This is how I did it in 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

The result is a vector like: [1 0 1 0 1 0 1 0...] 结果是像这样的向量:[1 0 1 0 1 0 1 0 ...]

Is there a way to get the same result with JavaScript? 有没有办法用JavaScript获得相同的结果?

You could mimic the function repmat with a while loop. 您可以使用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); 

Assuming you're looking for a way to add a 1 and then a 0, not an array containing 1 and 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/ https://jsfiddle.net/6seqs6af/1/

FWIW, here is the full repmat implementation in JavaScript. FWIW,这是JavaScript中的完整repmat实现。

It uses arrow functions ( => ) which isn't available in all browsers. 它使用并非在所有浏览器中都可用的箭头功能( => )。

  // 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()); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM