9969

Rearranging an array using for loop in Matlab

Question:

I have a 1 x 15 array of values:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

I need to rearrange them into a 3 x 5 matrix using a for loop:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

How would I do that?

Answer1:

I'm going to show you three methods. One where you need to have a for loop, and two others when you don't:

Method #1 - for loop

First, create a matrix that is 3 x 5, then keep track of an index that will go through your array. After, create a double for loop that will help you populate the array.

index = 1; array = 1 : 15; %// Array we wish to access matrix = zeros(3,5); %// Initialize for m = 1 : 3 for n = 1 : 5 matrix(m,n) = array(index); index = index + 1; end end matrix = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Method #2 - Without a for loop

Simply put, use reshape:

matrix = reshape(1:15, 5, 3).'; matrix = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

reshape will take a vector and restructure it into a matrix so that you populate the matrix by columns first. As such, we want to put 1 to 5 in the first column, 6 to 10 in the second and 11 to 15 in the third column. Therefore, our output matrix is in fact 5 x 3. When you see this, this is actually the <strong>transposed</strong> version of the matrix we want, which is why you do .' to transpose the matrix back.

Method #3 - Another method without a for loop (tip of the hat goes to Luis Mendo)

You can use vec2mat, and specify that you need to have 5 columns worth for your matrix:

matrix = vec2mat(1:15, 5); matrix = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

vec2mat takes a vector and reshapes it into a matrix of as many columns as you specify in the second parameter. In this case, we need 5 columns.

Answer2:

For the sake of (bsx)fun, here is another option...

bsxfun(@plus,1:5,[0:5:10]') ans = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

less readable, maybe faster, but who cares if it is such a small of an array...

Answer3:

A = [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ] ; A = reshape( A' , 3 , 5 ) ; A' = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Recommend

  • How to combine two image byte[] arrays together quickly utilizing a mask array in C#
  • Precision loss numpy - mpmath
  • scipy.ndimage.zoom result depends on image size
  • Replace any string in columns with 1
  • Web service not returning integer data in an object [duplicate]
  • Creating UDF with VSTO in Excel
  • How to set an entity field that does not exist on the table but does exists in the raw SQL as an ali
  • how to query for min or max inet/cidr with postgres
  • Javascript Array, Object, Date not defined
  • Laravel at least one field is required
  • Magento: where is the trigger of the custom cache?
  • insert radio value multiple data codeigniter in database to one row?
  • Can't get plist URL in Swift
  • sweetalert2 inputoptions from file in select example
  • What Makes These Two Array Adds Different?
  • JSON encode and decode on PHP
  • converter json to two dimensional array
  • Yii2: Finding file and getting path in a directory tree
  • KnockoutObservableArray with typed elements in TypeScript
  • Python ImageIO Gif Set Delay Between Frames
  • Clear activity stack before launching another activity
  • Add dynamic data to line chart from mysql database with highcharts
  • How to print columns containing value
  • Symfony 2. CSRF token is invalid
  • Make new pandas columns based on pipe-delimited column with possible repeats
  • How to assign byte[] as a pointer in C#
  • Convert Type Decimal to Hex (string) in .NET 3.5
  • Appending Character to Character Array In C
  • PHP CURL timing out but CLI CURL works
  • Declaring variable dynamically in VB.net
  • CakePHP 2.0.4 - findBy magic methods with conditions
  • Jackson Parser: ignore deserializing for type mismatch
  • Initializer list vs. initialization method
  • C# - Is there a limit to the size of an httpWebRequest stream?
  • Date difference with leap year
  • Rearranging Cells in UITableView Bug & Saving Changes
  • Benchmarking RAM performance - UWP and C#
  • Angular 2 constructor injection vs direct access
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Running Map reduces the dimensions of the matrices