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

In Matlab: Write a user-defined function that sorts the elements of a vector fro

ID: 3807798 • Letter: I

Question

In Matlab:

Write a user-defined function that sorts the elements of a vector 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 a descending order.

DO NOT use the MATLAB built-in functions sort, max, or min.

Test your function on a vector with 14 numbers (integers) randomly distributed between –30 and 30.

Use the MATLAB randi function to generate the initial vector.

Explanation / Answer

rand.m:
%Code to generate random numbers of user defined length
x=[];
a = input('Enter the number of values in the vector');
%using randi to generate random values with arguments range of values to be
%generated,(1 by a)vector of values
x=randi([-30,30],1,a);
%Displaying data in vector before sorting
disp('Before Sorting');
disp(x);
%calling function downsort to sort the values in the vector
downsort(x);


downsort.m:
%function to sorting the values in decreasing order
function s=downsort(x)
swap = 1;
%comparing the values using bubble sort
while swap
swap = 0;
for j = 1:numel(x)-1
%comparing and swapping the values
if x(j+1) > x(j)
temp = x(j);
x(j) = x(j+1);
x(j+1) = temp;
swap = 1;
end
end
end
s=x;
disp('Sorted order is');
disp(s);

output:
>> rand
Enter the number of values in the vector14
Before Sorting
-19 -16 -5 -27 25 27 -1 -1 -10 24 -8 -24 17 -7
Sorted order is
27 25 24 17 -1 -1 -5 -7 -8 -10 -16 -19 -24 -27

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote