How do you write a program that sorts an entire matrix in increasing order?
3 views (last 30 days)
Show older comments
THIS IS AN OLD TEST QUESTION THAT I COULD NOT FIGURE OUT. I would like to know how to solve this in its entirety please.
The values mus increase in the same order that a book is read. the program must work for any sized matrix. cannot use any built in sum functions or sort functions
Test with matrix B
B = [ -3 4 7; 9 11 -13; -17 19 -23; -29 31 37; 39 41 47]
3 Comments
Walter Roberson
on 27 Apr 2017
"The values mus increase in the same order that a book is read."
What does that mean?
The closest book to me is in Japanese, and it is is read in columns from top to bottom, right hand page and then left hand page, and then flip down a page from the left towards the right (the opposite order that English books increase in pages.) At the moment I do not know which order the columns are read in on any one page, but probably right-most column first.
Answers (1)
Image Analyst
on 27 Apr 2017
Edited: Image Analyst
on 27 Apr 2017
Pick a sorting algorithm and start coding. It's a bit too much to ask us to do it for you.
Start like this:
rowVector = reshape(B, 1, []);
[rows, columns] = size(B);
% Now sort row vector - you write the code...
% Now reshape back into matrix
sortedArray = reshape(sortedVector, [columns, rows]);
% Transpose to get into English "Book order"
sortedArray = sortedArray';
1 Comment
Joseph Cheng
on 27 Apr 2017
Edited: Joseph Cheng
on 27 Apr 2017
to help you out a bit more you can see what is happening here
B = [ -3 4 7; 9 11 -13; -17 19 -23; -29 31 37; 39 41 47];
[orow ocol]= size(B);
B=B(:)';
cindex = 1;
while cindex<=numel(B)
disp(cindex)
tomove = B<B(cindex);
disp(B)
check = find(tomove);
cindex=cindex+1;
B = [B(tomove) B(~tomove)];
disp(B);
end
B=reshape(B,ocol,orow)';
to follow Image Analyst's points you can also take a look at what i've coded here which gets you part of the way there and you'll learn more by understanding what needs to be done to finish this.
See Also
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!