Can someone please check my code?

2 visualizzazioni (ultimi 30 giorni)
Eduardo Gallegos
Eduardo Gallegos il 16 Dic 2022
Risposto: Nikhil il 19 Dic 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 Commento
Eduardo Gallegos
Eduardo Gallegos il 16 Dic 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))

Accedi per commentare.

Risposte (1)

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

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by