Can someone please check my code?

조회 수: 2 (최근 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