Concept explainers
To write:
A
Answer to Problem 10.1P
Solution:
The function file is,
%MATLAB code to create a function that will receive a value for r and calculate and return the sum of the geometric series and if a second argument is passed to the function, then the function generates a random integer for n.
%function file
function sum = geomser(r, varargin)
%define the function geomser.
arg = nargin;
if arg == 2
%if arguments are two then it will generate proper sum.
n = varargin{1};
%if only second argument is present then it will take a random integer
%for n.
else
n = randi([5, 30]);
end
s = 1;
for j = 1:n
s = s + r.^j;
end
sum = s;
end
%end of function file
%The function file should be placed in the same folder.
Explanation of Solution
The formula for to calculate the sum of a geometric series is given as,
Substitute 3 for r and 5 for n in the above formula.
MATLAB Code:
%MATLAB code to create a function that will receive a value for r and calculate and return the sum of the geometric series and if a second argument is passed to the function, then the function generates a random integer for n.
%function file
function sum = geomser(r, varargin)
%define the function geomser.
arg = nargin;
if arg == 2
%if arguments are two then it will generate proper sum.
n = varargin{1};
%if only second argument is present then it will take a random integer
%for n.
else
n = randi([5, 30]);
end
s = 1;
for j = 1:n
s = s + r.^j;
end
sum = s;
end
%end of function file
%The function file should be placed in the same folder.
Save the MATLAB function with name, geomser.m in the current folder. Execute the function file by typing the function name at the command window to generate output.
Result:
The result is,
Therefore, the result is stated above.
Want to see more full solutions like this?
Chapter 10 Solutions
MATLAB: A Practical Introduction to Programming and Problem Solving
- Algebra & Trigonometry with Analytic GeometryAlgebraISBN:9781133382119Author:SwokowskiPublisher:Cengage