Can someone please check my code?

2 views (last 30 days)
Eduardo Gallegos
Eduardo Gallegos on 16 Dec 2022
Answered: Nikhil on 19 Dec 2022
Here are the instructions : The purpose of this assignment is to demonstrate these MATLAB skills:
a. Code a function
b. Code a for loop that sums the terms of a series.
c. Use a conditional statement to break the loop
d. Display the sum after the for loop ends.
Part 1A: Code a Matlab function file called fcn1.m
This loop will sum the terms of a sequence.
The function’s inputs are:
b = a constant used in the calculations.
loop_limit = the value to break for loop.
The function’s output is:
total = the sum of the terms.
Part 1B: Inside this function:
Initialize total = 0;
Initialize term = zeros(1, 100);
Code a for loop with k = 1 to 100 that does the following:
a. Computes term(k) = pi/(12+ k^b);
b Adds term(k) to total. (This will be the sum of all the terms.)
c. Breaks the loop when the absolute value of term(k) is less than loop_limit
Part 2A : Create a Matlab test file that sets these parameters and calls your function:
b = 3;
loop_limit = 0.001
Part 2B:
In the test file, after the call to your function, use the disp() and num2str() functions to display the sum of the series.
Here is the function
function [total] = fcn1(x)
b = 3;
loop_limit = 0.001
total = 0;
term = zeros(1, 100);
for k = 1:100
term(k) = pi/(12+ k^b);
total = total + term(k);
if (term(k) < loop_limit)
break
end
end
end
The calling function
clc; close all; clear all;
y = fcn1(1)
disp(num2str(y))
Thank you so much.
  1 Comment
Eduardo Gallegos
Eduardo Gallegos on 16 Dec 2022
I made an adjustment to the code.
function
function [total] = fcn1(b,loop_limit)
total = 0;
term = zeros(1, 100);
for k = 1:100
term(k) = pi/(12+ k^b);
total = total + term(k);
if (term(k) < loop_limit)
break
end
end
end
Calling Function
clc; close all;
y = fcn1(3,0.001);
disp(num2str(y))

Sign in to comment.

Answers (1)

Nikhil
Nikhil on 19 Dec 2022
Hey Eduardo, you have covered all the required aspects in your code. It looks fine.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!