In: Computer Science
Matlab Programming
Write an M-file to read a real-valued vector of any length from the keyboard and sort it into descending order, i.e., rearrange all the numbers from the biggest one to the smallest one.
Please test your program with the following 9-element array:
input_vector=[-1, -11, 6,-17, 23, 0, 5, 9, -8]
MATLAB Code:
% MATLAB Script that reads a vector, Sort the vector in Descending order and prints
clc;
clear;
% Reading input vector from user
ipVec = input("Enter a vector: ");
% Sorting vector in descending order using Bubble Sort
Logic
% Set size to length of the array passed
size = length(ipVec);
% Outer loop runs from 1 to size
for outer_loop=1:size
% Inner loop runs from 1 to size-1
for inner_loop=1:size-1
% Comparing elements
if ipVec(inner_loop) < ipVec(inner_loop + 1)
% Swapping elements
temp = ipVec(inner_loop + 1);
ipVec(inner_loop + 1) = ipVec(inner_loop);
ipVec(inner_loop) = temp;
end %end if statement
end %end for inner_loop
end %end outer_loop
% Printing vector after sorting
fprintf("\nAfter Sorting in Descending Order: ");
disp(ipVec);
____________________________________________________________________________________________
Sample Run: