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

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);

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote