Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert simple array into two-dimensional array (matrix)

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.

like image 349
Bakhtiyor Avatar asked Dec 20 '10 17:12

Bakhtiyor


People also ask

How do I turn an array into a 2D array?

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.

How do you convert a one-dimensional array into two dimensions?

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.

How do you convert a one-dimensional array to a two-dimensional array in C?

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.


1 Answers

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]] 
like image 187
jwueller Avatar answered Sep 22 '22 17:09

jwueller