Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a Matlab function, called mysum that inputs the integer n and outputs the

ID: 2085404 • Letter: W

Question

Write a Matlab function, called mysum that inputs the integer n and outputs the sum of the first n integers. Use a for loop to compute the sum - don't use Matlab's built in function. Show your results for n = 20 and n = 100. Write a Matlab function, called myabsolutevalue that inputs a real number a and outputs the absolute value of a. Use a if loop to return the result - don't use Matlab's built in function. Test for a = ?2.3313224, and a = 9242.23. Check that your function myabsolutevalue treats the case a = 0. Use the command fprintf in your function to display your result.

Explanation / Answer

MATLAB code is provided below followed by the examples that it executes.

steps:

1. create a script file (.m file) called "calling_function" and copy the following code in it.

clc;
clear all;
close all;

n = input ('Enter n:');
sum = mysum(n);
display(sum);

a = input ('Enter a:');
absvalue = myabsolutevalue(a);
display(absvalue);

2. Now create two script files with names mysum and myabsolutevalue and copy the following code.

mysum:

function sum = mysum(n)
k = 0; % initialize a variable
for i = 1:n
k = k+i;
end
sum = k;
end

myabsolutevalue:

function absvalue = myabsolutevalue(a)
if (a<0)
a = -1*a;
end
absvalue = a;
end

3. place all three files in the same folder and run the calling_function.

then you must get the results as below.

Enter n:20

sum =

210

Enter a:-2.3343224

absvalue =

2.3343

Enter n:100

sum =

5050

Enter a:9242.23

absvalue =

9.2422e+003

Enter n:50

sum =

1275

Enter a:0

absvalue =

0

In the above examples are the cases are covered.

Hope this helps buddy :)

Thankyou...

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote