Please use MATLAB only. Also, please read and follow the instructions carefully.
ID: 2083016 • Letter: P
Question
Please use MATLAB only. Also, please read and follow the instructions carefully. Thank you. 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, 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 (except perhaps to verify your result). Test your function on a vector with 14 numbers (integers) randomly distributed between -30 and 30. Use the MATLAB rand function to generate the initial vector.Explanation / Answer
clc;
clear all;
close all;
% A=[1 2 9 4 5 6 7];
A=input('enter the array');%to enter any input array
swapped = 1;
while swapped
swapped = 0;
for i=1:numel(A)-1
if A(i+1) > A(i)
temp = A(i);
A(i) = A(i+1);
A(i+1) = temp;
swapped = 1;
end
end
end
disp(A)% it will give the descending order of the array
output:
enter the arraylinspace(-30,30,14)
Columns 1 through 11
30.0000 25.3846 20.7692 16.1538 11.5385 6.9231 2.3077 -2.3077 -6.9231 -11.5385 -16.1538
Columns 12 through 14
-20.7692 -25.3846 -30.0000
here i use linspace to generate 14 integer in between -30 to +30 but you can take any input array