我想要更新矩阵的一整列。
我首先初始化矩阵,如下所示:
m =({length:10}, (_,i) => Array.from({length:2}, (_,j) => i+'x'+j));然后,我有一个包含2个元素的数组(比如a2),我想通过操作将它放入矩阵的第j列。如果我使用matlab,我会做以下事情:m(:,j)=a2+ m(:,j)
我如何在javascript中做到这一点?
发布于 2020-06-08 17:23:58
你的意思是这样吗?
const m = Array.from({length:10}, (_,i) => Array.from({length:2}, (_,j) => i+'x'+j));
console.log("before", m);
const j = 2;
const a2 = "z"
const n = m.map(row => {row.splice(j, 0, a2); return row});
console.log("after", n);
操作前:
before [
[ "0x0", "0x1" ],
[ "1x0", "1x1" ],
[ "2x0", "2x1" ],
[ "3x0", "3x1" ],
[ "4x0", "4x1" ],
[ "5x0", "5x1" ],
[ "6x0", "6x1" ],
[ "7x0", "7x1" ],
[ "8x0", "8x1" ],
[ "9x0", "9x1" ]
]在操作之后(即,将"z“添加到第2列):
after [
[ "0x0", "0x1", "z" ],
[ "1x0", "1x1", "z" ],
[ "2x0", "2x1", "z" ],
[ "3x0", "3x1", "z" ],
[ "4x0", "4x1", "z" ],
[ "5x0", "5x1", "z" ],
[ "6x0", "6x1", "z" ],
[ "7x0", "7x1", "z" ],
[ "8x0", "8x1", "z" ],
[ "9x0", "9x1", "z" ]
]或者a2本身是否应该是一个数组?然后,简单的情况是,它是一个一维数组:
const m = Array.from({length:10}, (_,i) => Array.from({length:2}, (_,j) => i+'x'+j));
console.log("before", m);
const j = 2;
const a2 = Array.from({length:10}, (_,j) => 'z'+j)
const n = m.map((row, i) => {row.splice(j, 0, a2[i]); return row});
console.log("after", n);
操作后(即在第2列中添加"z{ i }“):
after [
[ "0x0", "0x1", "z0" ],
[ "1x0", "1x1", "z1" ],
[ "2x0", "2x1", "z2" ],
[ "3x0", "3x1", "z3" ],
[ "4x0", "4x1", "z4" ],
[ "5x0", "5x1", "z5" ],
[ "6x0", "6x1", "z6" ],
[ "7x0", "7x1", "z7" ],
[ "8x0", "8x1", "z8" ],
[ "9x0", "9x1", "z9" ]
]或者更复杂的情况,当a2是二维数组时:
const m = Array.from({length:10}, (_,i) => Array.from({length:2}, (_,j) => i+'x'+j));
console.log("before", m);
const j = 2;
const a2 = Array.from({length:10}, (_,i) => Array.from({length:2}, (_,j) => i+'z'+j));
const n = m.map((row, i) => {row.splice(j, 0, a2[i]); return row.flat()});
console.log("after", n);
操作后(即在第2列中添加"z{ i }“):
after [
[ "0x0", "0x1", "0z0", "0z1" ],
[ "1x0", "1x1", "1z0", "1z1" ],
[ "2x0", "2x1", "2z0", "2z1" ],
[ "3x0", "3x1", "3z0", "3z1" ],
[ "4x0", "4x1", "4z0", "4z1" ],
[ "5x0", "5x1", "5z0", "5z1" ],
[ "6x0", "6x1", "6z0", "6z1" ],
[ "7x0", "7x1", "7z0", "7z1" ],
[ "8x0", "8x1", "8z0", "8z1" ],
[ "9x0", "9x1", "9z0", "9z1" ]
]发布于 2020-06-08 18:00:50
我认为使用Array.prototype.forEach和Array.prototype.splice是实现这一点的好方法:
// Setup for demo
const Row = (w) =>Array.from({length:w}).fill('').map((c,i)=>c=i);
const Matrix = (h, w) => Array.from({length:h}).fill('').map(r=>r=Row(w));
const print = (mtx) => mtx.forEach(r=>console.log([...r].join(", ")));
// Original state of matrix
const m1 = Matrix(2,10);
print(m1);
console.log('----------');
// Insertion function
const insertCol = (mtx, cInd, newCol) => {
mtx.forEach( (row, rInd) => { row.splice(cInd, 0, newCol[rInd]); }
);
}
// Matrix with inserted column
const someCol = ['X','Y'];
insertCol(m1, 3, someCol);
print(m1);
https://stackoverflow.com/questions/62256715
复制相似问题