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

per isakson
per isakson 2019년 2월 24일
"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 2019년 2월 24일
편집: Stephen23 2019년 2월 24일
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 2019년 2월 24일
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 2019년 2월 24일
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