Sort Matrix without the sort (Homework)

Hey guys, I need to sort a matrix from highest to lowest by selection without using the built in function. The teacher gave us function for a vector but I don't understand how to apply it to a matrix. Here is the function he gave us:
function B=SelecD(A)
for i=1:length(A)-1
highest=i;
for j=i+1:length(A)
if A(j) > A(highest)
highest=j;
end
end
A=Swap(A,i,highest);
disp(A);
end
B=A;
end
Thank you for your help

5 个评论

"sort a matrix" what exactly does that mean? Describe that in plain English.
There is no function named Swap in Matlab.
if I have A=[5 9 1;2 6 4;3 8 7] I want B=[9 8 7;6 5 4;3 2 1]
And swap is another function my teacher created:
function C=Swap(A,m,n)
temp=A(m); A(m)=A(n); A(n)=temp;
C=A;
Your teacher should learn how to write efficient MATLAB code. Instead of defining a pointless separate function to swap two elements, it would be simpler, neater, and faster to use basic MATLAB indexing on that line:
A([i,highest]) = A([highest,i]);
They should also learn to follow better code practices (e.g. not putting everything onto one line).
"The teacher gave us function for a vector but I don't understand how to apply it to a matrix. "
This should get you started: transpose, reshape, sort, reshape, transpose.
Note if your teacher had written more robust code (using reliable numel rather than the beginners' favorite length) then the reshape calls would not be required either.
I can't guess what approach your teacher want you to use for this task. Maybe, you can guess based on what you done in the class so far.
Given wooden squares with numbers and a large table. How would you make this sorting manually?
Thanks both of you. Stephen's solution was perfect.

请先登录,再进行评论。

回答(0 个)

类别

帮助中心File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

产品

版本

R2018b

提问:

2019-2-24

评论:

2019-2-24

Community Treasure Hunt

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

Start Hunting!

Translated by