Populating matrix with coordinates of each element
5 views (last 30 days)
Show older comments
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
Accepted Answer
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)).'
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))
2 Comments
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
Transposing gives the correct orientation.
result = result.'
More Answers (0)
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!