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

MATLAB Hello, I need a code for this please. Recall that a geometric sum is a su

ID: 3790900 • Letter: M

Question

MATLAB

Hello, I need a code for this please.

Recall that a geometric sum is a sum of the form a + ar + ar^2 + ar^3 + .... Write a function file that accepts the values of r, a and n as arguments and uses a for loop to return the sum of the first n terms of the geometric series. Test your function for a = 5, r = 1/3 and n = 8. Write a function file that accepts the values of r, a and n as arguments and uses the built in command sum to find the sum of the first n terms of the geometric series. Test your function for a = 5, r = 1/3 and n = 8.

Explanation / Answer

%matlab code

%part a
function sum = geometricSum(r,a,n)
    sum = 0;
    for i=1:n+1
        sum = sum + a*r^(i-1);
    end
end

fprintf("Sum of Geometric series with a = 5, r = 1/3 and n = 8 is %f ",geometricSum(1/3,5,8));
%output: Sum of Geometric series with a = 5, r = 1/3 and n = 8 is 7.499619

%part b
function sum = getSum(r,a,n)
    %create vector and fill vector
    R = [];
    for i=1:n+1
        R(i) = a*r^(i-1);
    end
    % determine sum using built in sum function
    sum = sum(R);
end

fprintf("Sum of Geometric series with a = 5, r = 1/3 and n = 8 is %f ",getSum(1/3,5,8));
%output: Sum of Geometric series with a = 5, r = 1/3 and n = 8 is 7.499619