Sort Columns by ascending order while maintaing cell values in place for every row

3 views (last 30 days)
I have a code that will create a matrix (32xM) with each column being a random permutation of 32.
for k =1:100 %For however many trials (100 in this case)
p(:,k)= randperm(32); %Create a permutation of 32 in each column
end
Is there a way to now order the random permutations in ascending order without losing the order of permuation? To clarify, can I order an entire column to sort based on its first cell value in ascending order? This should result in the random permutations being organized from least to greatest.

Answers (1)

Scott MacKenzie
Scott MacKenzie on 3 Jun 2021
Edited: Scott MacKenzie on 3 Jun 2021
Hmmm, I think this works...
for k =1:100 %For however many trials (100 in this case)
p(:,k)= randperm(32); %Create a permutation of 32 in each column
end
q = sortrows(p',1:32);
q = q'
Here's an example with smaller values to show the sorting result:
for k =1:8
p(:,k)= randperm(5);
end
p
q = sortrows(p',1:5);
q = q'
p =
3 1 5 5 1 2 1 3
4 4 3 3 5 5 4 4
1 5 2 2 4 4 3 2
2 2 4 1 3 3 2 1
5 3 1 4 2 1 5 5
q =
1 1 1 2 3 3 5 5
4 4 5 5 4 4 3 3
3 5 4 4 1 2 2 2
2 2 3 3 2 1 1 4
5 3 2 1 5 5 4 1

Categories

Find more on Shifting and Sorting 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!