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 Kommentare

per isakson
per isakson am 24 Feb. 2019
"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;
Stephen23
Stephen23 am 24 Feb. 2019
Bearbeitet: Stephen23 am 24 Feb. 2019
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.
per isakson
per isakson am 24 Feb. 2019
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?
poolman21
poolman21 am 24 Feb. 2019
Thanks both of you. Stephen's solution was perfect.

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Kategorien

Produkte

Version

R2018b

Gefragt:

am 24 Feb. 2019

Kommentiert:

am 24 Feb. 2019

Community Treasure Hunt

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

Start Hunting!

Translated by