Consider the following code that checks to see if an array is sorted. Create ano
ID: 3866707 • Letter: C
Question
Consider the following code that checks to see if an array is sorted. Create anonymous functions for each of the following cases that responds with true if the first argument is less than the second. Finally show how to invoke is Sortcd to answer the requests that follow: (a) Compare two fractions (each a struct with numerator and denominator) to see if the first is less than the second. The array of fractions to verify is called fractions. (b) Compare two times according to their occurrence in the day. A time is a struct with three numeric fields hour, min and see. The array of times to verify is called times. function s = is Sorted(a, cFun) s = true: for ii = 2: length(a) if ~ c Fun(a(ii-i), a(ii)) s = false: end endExplanation / Answer
a) create a file named cFun.m and paste given code into it.
cFun.m
function [flag] = cFun(r1,r2)
if((r1.numerator/r1.denominator) <= (r2.numerator/r2.denominator) )
flag = true;
else
flag = false;
end
end
Sample run:
For verifying the isSorted fuction please create a file named isSorted.m and paste following code into it.
isSorted.m
function s = isSorted(a,cFun)
s = true;
for ii = 2:length(a)
if(~cFun( a(ii - 1), a(ii) ))
s = false;
end
end
end
Sample Run:
b) create a file named cFun.m and paste given code into it.
cFun.m
function [flag] = cFun(r1,r2)
if( (r1.hour) < (r2.hour) )
flag = true;
elseif((r1.hour) == (r2.hour))
if((r1.min) < (r2.min))
flag = true;
elseif((r1.min) == (r2.min))
if((r1.sec) < (r2.sec))
flag = true;
elseif((r1.sec) == (r2.sec))
flag = true;
else
flag = false;
end
elseif((r1.min) > (r2.min))
flag = false;
end
elseif((r1.hour) > (r2.hour))
flag = false;
end
end
Sample run:
Sample run of isSorted:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.