Populating matrix with coordinates of each element

3 views (last 30 days)
Hi Guys,
I am trying to populate a 100x100 matrix so that the first element is assigned to 1 and the last element is assigned to 100.
Any suggestions? I've already create the specified matrix using zeros and ones but I am guessing I have to use a nested for-loop with the outer looping over the rows and the inner looping over the columns to reassign each element?
Any assistance would be much appreciated.
  5 Comments
Will Pihir
Will Pihir on 30 Aug 2021
Yeah I just figured it out as I was typing.
Oops.
Same premise still applies
Matt J
Matt J on 30 Aug 2021
Same premise still applies
Then, you should respond to the answer that you have been given by @DGM. Accept-click the answer if it does what you want and describe what is missing if it does not.

Sign in to comment.

Accepted Answer

DGM
DGM on 29 Aug 2021
Edited: DGM on 29 Aug 2021
For your example using row-wise linear indexing:
s = [5 10]; % output size
reshape(1:prod(s),s(2),s(1)).'
ans = 5×10
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
Obviously, you'd change s to suit your needs. To do the same thing columnwise:
s = [5 10]; % output size
reshape(1:prod(s),s(1),s(2))
ans = 5×10
1 6 11 16 21 26 31 36 41 46 2 7 12 17 22 27 32 37 42 47 3 8 13 18 23 28 33 38 43 48 4 9 14 19 24 29 34 39 44 49 5 10 15 20 25 30 35 40 45 50
  2 Comments
Will Pihir
Will Pihir on 31 Aug 2021
Thanks for the answer DGM. This was exactly what I was looking for.
Just so I can understand it better, what does the syntax .' at the end of the row-wise linear indexing code do?
DGM
DGM on 31 Aug 2021
.' transposes the array. For a 2D array, t's the same as doing
Atranspose = permute(A,[2 1]);
Since reshape() fills the result along columns, and the requirements need the indices ordered along rows, I have reshape generate the transpose of the desired array (hence the dimension order swap).
s = [5 10]; % output size
result = reshape(1:prod(s),s(2),s(1)) % with no transpose
result = 10×5
1 11 21 31 41 2 12 22 32 42 3 13 23 33 43 4 14 24 34 44 5 15 25 35 45 6 16 26 36 46 7 17 27 37 47 8 18 28 38 48 9 19 29 39 49 10 20 30 40 50
Transposing gives the correct orientation.
result = result.'
result = 5×10
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

Sign in to comment.

More Answers (0)

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!