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

I am having a problem answering Exercise 28 of Chapter 12 in the book by Attaway

ID: 662405 • Letter: I

Question

I am having a problem answering Exercise 28 of Chapter 12 in the book by Attaway ( Matlab: A Practical Introduction to Programming and Problem Solving by Stormy Attaway -3rd edition).

the question is asking the following: ('Write a function that will receive a vector and will return two index vectors: one for

ascending order and one for descending order. Check the function by writing

a script that will call the function, and then use the index vectors to print the

original vector in ascending and descending order.')

Thanks

Explanation / Answer

prog.m

function [ascendingIndex,descendingIndex]= prog(arr)
   ascending =sort(arr,'ascend')
   [rows,cols]=size(arr)
   ascendingIndex=ones(1,cols)
   descendingIndex=ones(1,cols)
   for i=1:cols
       for j=1:cols

           if ascending(1,i) == arr(1,j)
               ascendingIndex(1,i)=j;
           end
       end
   end
   descending =sort(arr,'descend')
   for i=1:cols
       for j=1:cols
           if descending(1,i)==arr(1,j)
               descendingIndex(1,i)=j;
           end
       end
   end
end

script

arr = [2,4,11,24,5,9]
[ascendingIndex,descendingIndex]=prog(arr)
[rows,cols]=size(arr)
print "Ascending Order"
for i=1:cols
   fprintf ('%i ',arr(ascendingIndex(i)))
end
fprintf(" ");
print "Descending Order"
for i=1:cols
   fprintf ('%i ',arr(descendingIndex(i)))
end
fprintf(" ");