Write a user-defined function that sorts the elements of a matrix. For the funct
ID: 3540660 • Letter: W
Question
Write a user-defined function that sorts the elements of a matrix. For the function name and arguments use B = matrixsort(A), where A is any size matrix and B is a matrix of the same size with the elements of A rearranged in descending order row after row with the (1,1) element the largest and the (m, n) element the smallest. Test your function on a 4 x 7 matrix with elements (integers) randomly distributed between( -30 and 30). Use MATLAB's randi function to generate the initial matrix.
please try to solve this problem by converting the matrix to a vector using the a sort functiion then reconverting it back to a matrix , please comment your steps in the code so i can understand your logic thanks.
Explanation / Answer
% required function
function B = matrixsort(A)
% getting rows and columns of A
[r,c]=size(A);
% converting A to vector
vec = A(:);
% sorting vector in descending order
vec = sort(vec,1,'descend');
% reshaping vector back to original matrix dimensions
B = reshape(vec,c,r)';
end
% end of function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% TESTING above function
% creating 4 x 7 random matrix
A = randi([-30,30],4,7);
% sorting matrix
B = matrixsort(A);
% displaying result
disp('Sorted matrix is:');
disp(B);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.