Can someone please check my code?

1 次查看(过去 30 天)
Eduardo Gallegos
Eduardo Gallegos 2022-12-16
回答: Nikhil 2022-12-19
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 个评论
Eduardo Gallegos
Eduardo Gallegos 2022-12-16
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))

请先登录,再进行评论。

回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by