Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

MATLAB question Write a user-defined function that sorts the elements of a vecto

ID: 2085433 • Letter: M

Question

MATLAB question

Write a user-defined function that sorts the elements of a vector (of any length) from the largest to the smallest. For the function name and arguments use y = downsort (x). The input to the function is a vector x of any length, and the output y is a vector in which the elements of x are arranged in descending order. Do not use the MATLAB sort function. Test your function by using it in the Command Window to rearrange the elements of the following vector: [-2, 8, 29, 0, 3, -17, -1, 54, 15, -10, 32].

Explanation / Answer

downsort.m

function y = downsort(x)
for i=1:length(x)
for j=i+1:length(x)
if x(j)>x(i)%bringing bigger value to the current index i
temp = x(j);
x(j) = x(i);
x(i) = temp;
end
end
end
y=x;
end

Command window log:

>> downsort([-2 8 29 0 3 -17 -1 54 15 -10 32])

ans =

Columns 1 through 8

54 32 29 15 8 3 0 -1

Columns 9 through 11

-2 -10 -17

>>