In: Computer Science
Write a function ‘sort1’ that takes in an array of non-zero
positive integers as input and returns a second vector
that contains only the odd numbers. It will return zero if all
elements are even. Use error-traps to check against
probable errors in user input. In case of an error, it will return
NaN. You are allowed to use Matlab built-in function
round(). Check your code with the following arrays:
>> y1 = [18, -5, 89, -7, 4, 10, 12, 34, -2, 45];
>> y2 = [34, 67, 89, 0, 12, 87, 0, 5];
>> y3 = [ 8, 3, 11, 4, 7, 12, 19, 3, 5, 6]
>> z1 = sort1(y1)
z1 =
NaN
>> z2 = sort1(y2)
z2 =
NaN
>> z3 = sort(y3)
z3 =
3 11 7 19 3 5
** You cannot use any built in Matlab functions other than round(). I don't need all the test runs. I'm just stuck halfway through the code and can't finish it.
function odd_array = sort1(array)
% Matlab function that takes in an array of non-zero positive
integers as input and returns a second vector
% that contains only the odd numbers
% It will return zero if all elements are even.
% In case of an error, it will return NaN
odd_array = 0;
k=0;
% loop over the array
for i =1:length(array)
% if array contains any negative or zeros , set odd_aray to NaN
and
% end the loop
if(array(i) <= 0)
odd_array = NaN;
break;
% if array contains any decimal values, set odd_array to NaN and
end the loop
elseif((round(array(i),1) - round(array(i))) > 0)
odd_array = NaN;
break;
% if ith element is odd, add ith element to odd_array
elseif((round(array(i)/2,1)-round(array(i)/2)) ~= 0)
k = k +1;
odd_array(k) = array(i);
end
end
end
%end of function
Output: