Imagine I have an array:
A = Array(1, 2, 3, 4, 5, 6, 7, 8, 9);
And I want it to convert into 2-dimensional array (matrix of N x M), for instance like this:
A = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9));
Note, that rows and columns of the matrix is changeable.
Use reshape() Function to Transform 1d Array to 2d Array The number of components within every dimension defines the form of the array. We may add or delete parameters or adjust the number of items within every dimension by using reshaping. To modify the layout of a NumPy ndarray, we will be using the reshape() method.
Create a 2d array of appropriate size. Use a for loop to loop over your 1d array. Inside that for loop, you'll need to figure out where each value in the 1d array should go in the 2d array. Try using the mod function against your counter variable to "wrap around" the indices of the 2d array.
Call the function input_array to store elements in 1D array. Call the function print_array to print the elements of 1D array. Call the function array_to_matrix to convert 1D array to 2D array. Call function print_matrix to print the elements of the 2D array.
Something like this?
function listToMatrix(list, elementsPerSubArray) { var matrix = [], i, k; for (i = 0, k = -1; i < list.length; i++) { if (i % elementsPerSubArray === 0) { k++; matrix[k] = []; } matrix[k].push(list[i]); } return matrix; }
Usage:
var matrix = listToMatrix([1, 2, 3, 4, 4, 5, 6, 7, 8, 9], 3); // result: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With