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

just solve using matlab !!! please Given matrix C, write a program that sorts ea

ID: 3109986 • Letter: J

Question

just solve using matlab !!! please

Given matrix C, write a program that sorts each row in the matrix. If the row is an odd numbered row, sort that row from smallest to largest. If the row is an even numbered row, sort that row from largest to smallest. Once this is completed, create a new matrix of the same size that is populated with the difference between the new values and the original values. For example An is initially 13, but once the first row is sorted it will have a value of -5, so the new matrix will have a value of-18. Display the sorted matrix and the 'difference' matrix to the screen. C = [13 21 1 3 4 -5 7 17 13 7 0 7 8 1 0 -11 19 23 1 2 5 51 10 1.7 19 2 44 30 123 4 -4 12 6 77 8 0 0 5 0 -1 8 2] Your program must work for any size matrix. You cannot use sort or sum or any such Matlab functions. If you are in any doubt about what functions you can use, please raise your hand.

Explanation / Answer

%%%%%%Function definition%%%%

%%%For ascending sort

function g = sort_ascending (d)

for n=1:length(d)
for m=n+1:length(d)
if (d(m) < d(n))
temp=d(m);
d(m)=d(n);
d(n)=temp;
end
end
end
g=d;

%%%% For descending sort

function g = sort_descending (d)

for n=1:length(d)
for m=n+1:length(d)
if (d(m) > d(n))
temp=d(m);
d(m)=d(n);
d(n)=temp;
end
end
end
g=d;

%%%% Main Programm

clc;
clear all;
close all;
format short
A=[13 21 1 3 4 -5 7; 17 13 7 0 7 8 1 ; 0 -11 19 23 1 2 5; 51 10 1.7 19 2 44 30 ; 123 4 -4 12 6 77 8; 0 0 5 0 -1 8 2];
[m,n]=size(A);
G=zeros(m,n); %%%% Sorted matrix initially taken as zero matrix
for n= 1:m
if (rem(n,2)==1)
G(n,:)= sort_ascending(A(n,:));
else
G(n,:)= sort_descending(A(n,:));
end
end

D=A-G;
display('After sorting matrix is ');
G
display('Difference of original and sorted matrix is ');
D

Output :

After sorting matrix is

G =

-5.0000 1.0000 3.0000 4.0000 7.0000 13.0000 21.0000
17.0000 13.0000 8.0000 7.0000 7.0000 1.0000 0
-11.0000 0 1.0000 2.0000 5.0000 19.0000 23.0000
51.0000 44.0000 30.0000 19.0000 10.0000 2.0000 1.7000
-4.0000 4.0000 6.0000 8.0000 12.0000 77.0000 123.0000
8.0000 5.0000 2.0000 0 0 0 -1.0000

Difference of original and sorted matrix is

D =

18.0000 20.0000 -2.0000 -1.0000 -3.0000 -18.0000 -14.0000
0 0 -1.0000 -7.0000 0 7.0000 1.0000
11.0000 -11.0000 18.0000 21.0000 -4.0000 -17.0000 -18.0000
0 -34.0000 -28.3000 0 -8.0000 42.0000 28.3000
127.0000 0 -10.0000 4.0000 -6.0000 0 -115.0000
-8.0000 -5.0000 3.0000 0 -1.0000 8.0000 3.0000