PROBLEM 4 (10%) MATLAB: Write a for loop to calculate the sum of the squares of
ID: 1715332 • Letter: P
Question
PROBLEM 4 (10%)
MATLAB: Write a for loop to calculate the sum of the squares of all of the odd integers from 3 to 303 while subtracting the even integers (inclusive), i.e., find
32-4+52+...-302+3032,
and then divide the sum by pi. Output the result to three decimal place using fprintf. To do this,
first write a for loop that increments a number by 1 with every pass through it. Within the loop check whether the number is even or odd using if-else-end statements and perform the necessary mathematical operations. To check even or odd, try the rem or mod functions. The keyboard command is useful for debugging the code while it is executing.
Explanation / Answer
Answer is 1483135.9485
%%Matlab Program done in MATLAB R2015A
%sum of squares of oddd integers minus sum of all even integers
%division by pi
%range: 3 to 303
%Variables
sum = 0;
inbound =3;
outbound = 303;
res=0;
for i = inbound:outbound
if mod(i,2)==0
%even number check
sum = sum-i;
else
%Odd number check
sum = sum+(i*i);
end
end
res=sum/pi;
disp(['The result of the expression is:', num2str(res)]);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.