Simple Matlab functions 7) Write a function extract odds that takes an array of
ID: 3882045 • Letter: S
Question
Simple Matlab functions
7) Write a function extract odds that takes an array of random integers (you can generate this with the Matlab command v = randi(0501100, 1)):) and returns only the elements of the array that are even, using an if...else statement. 8) Write a function extract_odds_or_evens that takes two inputs: an array of random integers like in (7) and a second parameter that is either the string 'odd' or 'even'. Use combinations of a for loop and up to two if...else statements to extract either the odd or even numbers based on the second parameter and return the result.Explanation / Answer
7)
-------------------------------extract_odds.m---------------------------
function [arr] = extract_odds(v)
% store the size of the array that contains
% only even elements
n = 0;
for i = 1 : length(v)
% if the current element is even
if mod(v, 2) == 0
n = n + 1;
end
end
% create a vector of length n
arr = [ 1 : n ];
index = 1;
for i = 1 : length(v)
% if the current element is even
if mod(v(i), 2) == 0
arr(index) = v(i);
index = index + 1;
end
end
end
--------------------------main.m------------------------------
v = randi([0,50], [100,1]);
arr = extract_odds(v);
disp(arr);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.