Create Multiple Arrays While Looping Through One Single Array
40 views (last 30 days)
Show older comments
Zachary Giovanelli
on 19 Sep 2021
Commented: Zachary Giovanelli
on 21 Sep 2021
I would like to loop through an array of 81 elements. For evey 9 iterations through the loop I would like to create a new array assigned to a different variable name. Basically, what I want is to loop through the array that has 81 elements for a set of 9 times that will create a new array of 9 elements. I would like to continue this for the entire 81 elements. So basically 1:9 of array 81 = 1st New Array, then 10:18 of array 81 = 2nd New Array and then 19:27 of array 81 = 3rd New Array and this pattern would continue until the array of 81 elements has been sorted into 9 array with 9 elements each.
Example PseudoCode
Array81 = [1 2 3 4 5 6 ................ 81]
For Loop:
Loop through array81 and create the following:
1stNewArray = [1 2 3 4 5 6 7 8 9]
2ndNewArray = [10 11 12 13 14 15 16 17 18]
3rdNewArray = [19 20 21 22 23 24 25 26 27]
4thNewArray = [28 29 30 31 32 33 34 35 36]
This will continue until the 9thNewArray = [73 74 75 76 77 78 79 80 81]
Accepted Answer
Stephen23
on 20 Sep 2021
By far the simplest and most efficient solution is to use one matrix:
V = 1:81
M = reshape(V,9,9).'
You can trivially access the rows of the matrix using very basic MATLAB indexing, e.g. the third row:
M(3,:)
This is simpler and much more efficient than the slow, inefficient, complex creation of lots of separate variables:
When you are starting to learn MATLAB is the right time to learn how to write good MATLAB code.
7 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!