14:440:127- Introduction to Computers for Engineers
Problems for students to attempt in Recitation 7- Solutions
1)
Use a 'for loop' to calculate the sum of all prime numbers from 1000 to 2000.
s = 0;
for
x= 1000:2000
if
(isprime(x))
s=s+x;
end
end
disp(s)
2)
Use a 'while loop' to calculate the sum of all prime numbers from 1000 to 2000.
s = 0;
x=1000;
%different
while
(x<=2000)
%different
if
(isprime(x))
s=s+x;
end
x=x+1;
%different
end
disp(s)
3)
What sequence of numbers will be displayed by the following ‘for loop’?
n = 10;
for j = 1:n
n = n-1
j
end
9,1,8,2,7,3,6,4,5,5,4,6,3,7,2,8,1,9,0,10
4)
Define values for three variables of your choosing.
Write an anonymous function that
switches the values of variables one and two and another that does so for variables two
and three.
switcheroo12 = @(x,y,z) deal(y,x,z)
switcheroo23 = @(x,y,z) deal(x,z,y)
(Note… this wasn’t a very good question since you needed to use the deal( ) function,
which you haven’t seen before
)
5)
Write a program to plot the curve y=sin(x)+cos(x) within [0,2
π
].
a) use fplot and a normal user-defined function.
[In the mfile myfunc.m]
function
y = myfunc(x)
y=sin(x)+cos(x);
[In the workspace]
fplot('myfunc(x)',0:2*pi)