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

MATLAB ASSIGNMENT Write a MATLAB program that will add all the numbers correspon

ID: 2085555 • Letter: M

Question

MATLAB ASSIGNMENT

Write a MATLAB program that will add all the numbers corresponding to the even indices of an array. For instance, if the array x was x = [1, 3, 5, 10], then it should return 13 (- 3 + 10). Use that program to find the sum of all ever integers from 1 to 17. Write your program so that it is flexible. That is, you should be able to invoke your program from the command window as follows: > > y = addeven(x) % x is the input vector, and y is the sum of all the numbers corresponding to the even indices of x.

Explanation / Answer

Define a function in MATLAB as given below

function y = addeven(x)

%This function adds all the numbers placed at even digits of the input x

% y = the sum

% x = the input vector whose elements have to be checked

n = size(x,2); % n denotes the number of elements in input vector x

r = mod(n,2); %r = remainder after dividing n by 2

% if r = 1, then number of elements in x is odd

% if r = 0, then number of elements in x is even

sum = 0;

if r==1 %if number of elements in x is odd

%loop from 1st even digit place to last even digit place

%1st even digit place, i = 2 and last even digit place, i = n-1

    for i = 2:2:n-1

      sum = sum+x(i);

    end

elseif r==0 %if number of elements in x is even

%loop from 1st even digit place to last even digit place

%1st even digit place, i = 2 and last even digit place, i = n

    for i = 2:2:n

        sum = sum+x(i);

    end

end

y = sum;

end

Output:

x = [1 2 3 4 5 6];

>> y = addeven(x)

y =

    12

>> x = [2 5 6 8 1 4 9];

>> y = addeven(x)

y =

    17