Exercises On Matlab Functions
Exercises On Matlab Functions
(1) Write a function that would evaluate the following function to n terms:
function[y]=repeatprod(n)
q=1;
for m=1:n
p=1+.2*(m-1);
q=q*p;
end
y=q;
(2) Write a function that would determine the number of terms needed so that the
product P = 1 × 3 × 5 × 7 × 9 × ......(2n − 1) just exceed a given number, N. Use the
while loop.
function[y]=prodlimit(N)
p=1;m=0;
while p<=N
m=m+1;
p=p*(2*m-1);
end
y=m;
(3) Write a function that would take as input a row matrix of any length and converts
each of its elements to either 0 or 5 according to the following rule: If the element
is a negative number, convert to 0, if it is zero or positive, convert to 5. Use the
for and the if …. else statements.
1
(4) Write a function that would take as input an m × n matrix of any size and converts
each of its elements to either 0 or 5 according to the following rule: If the element
is a negative number, convert to 0, if it is zero or positive, convert to 5. Use the
for and the if …. else statements. (Note Example 4.4 on page 12 of your notes .
You need two for loops to address each element of an m × n matrix).
function[y]=sortmatrix(x) %x and y are matrices
L1=length(x(:,1)); %x has L1 rows
L2=length(x(1,:)); %x has L2 columns
%x is a L1 by L2 matrix.
K=zeros(L1,L2) %set aside a zero matrix of size L1 by L2
for m=1:L1
for mm=1:L2
A=x(m,mm); %take each element of x one at a time
if A<0
K(m,mm)=0;
else
K(m,mm)=5;
end
end
end
y=K;
1
(5) The expression, CF = , where the a’s are integers is called a
1
a1 +
1
a2 +
1
a3 +
a4
continued fraction. One shorthand for this is the row vector: [a1 a 2 a 3 a 4 ].
1
For example, [2 6 5] = = 0.4627 . Write a function that takes as an
1
2+
1
6+
5
input a row vector of any length and evaluates the continued fraction that it
represents. Use the for loop.