Chapter 2
Chapter 2
MATLAB
Author
image here
For: iterative statement
Iterative applications
If: conditional statement
Conditional applications
Outline
The for loop
Example 1:
Find the sum of the integers from 5 to 100.
3
Solution
4
Example 2
sum=0;
for i=1:2:100
sum=sum+i;
end
disp(‘sum of odd integers between 1 and 100 is:’);
disp(sum)
5
Example 3
6
Functions (reminder)
7
Example 4
Write a function “sumN” that finds the sum of the first N term of the
series below. 1 1 1 1 1 1 1 1
1 ....
2 3 4 5 6 7 8 N
function s=sumN(N)
s=0;
for i=1:N
s=s+1/i;
end
Write a function “expN” that finds the sum of the first N term of the
series below for a given value of x. N x i
i!
i 0
function s=expN(N,x)
s=0;
for i=0:N
s=s+x^i/factorial(i);
end
11
Example 1 n1=input('enter number1 ');
Create a program that accepts two n2=input('enter number2 ');
numbers and display the bigger
one if n1>n2
disp(n1)
else
disp(n2)
end
12
Example 2 n1=input('enter number1 ');
Create a program that compares n2=input('enter number2 ');
two numbers inputted by the user
and display the comparison result if n1>n2
disp('n1>n2')
elseif n1<n2
disp('n1<n2')
else
disp('the numbers are identical')
end
13
Example 3 nrows = 6;
ncols = 6;
1-Create a matrix and fill it with 1
A = ones(nrows,ncols)
2-Loop through the matrix and
assign each element a new value: for c = 1:ncols
2 on the main diagonal for r = 1:nrows
end
end
A
14
Example 4 syms hw pr mt et total
nbr=input('enter the number of student ')
Create a program that collects the
n students’ grades (Homework, for i=1:nbr
Project, mid-term & End-term) and fprintf('student %i\n',i)
hw(i)=input('enter the homework grade ');
determines if the student has pr(i)=input('enter the project grade ');
passed or failed the course mt(i)=input('enter the midterm exam grade ');
et(i)=input('enter the endterm exam grade ');
end
for i=1:nbr
moy(i)=hw(i)+pr(i)+mt(i)+ et(i);
end
for i=1:nbr
if moy(i)<60
fprintf('student %i got %d,
so he has failed\n',i,moy(i))
else
fprintf('student %i got %d, so he
has passed\n',i,moy(i))
end
end
15
Homework 2
Redo the previous example
while taking all possible
grades (F, D, D+, C, C+, B,
B+, A & a+) into account