Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

MATLAB Lecture - 8 2018

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

2017-18 Spring DERS 8

Nested for loop

Ex:
clear all !!!!
clc 1*1=1
1*2=2
for x=1:3 ====
display('! ! ! !') !!!!
for y=1:2
2*1=2
fprintf('%g * %g = %g\n',x,y,x*y)
2*2=4
end
display('= = = =') ====
end !!!!
display(' SON ') 3*1=3
3*2=6
====
SON
>>

Ex: Multiplication Table


clear all
clc

for x=1:10
display(' ')
for y=1:10
fprintf('%g * %g = %g\n',x,y,x*y)
end
end
display(' SON ')

Calculating Factorials

n!=1.2.3.4…(n-1).n

0!=1
1!=1
5!=1.2.3.4.5 = 120

1
2017-18 Spring DERS 8

An algorithm for calculating factorials:

0!=1
___________________

1!=1.1 =0!.1
2!=1.1.2 =1!.2
3!=1.1.2.3 =2!.3
4!=1.1.2.3.4 =3!.4
5!=1.1.2.3.4.5 =4!.5
. .
. .
. .
n!= =(n-1)!.n

n!=(n-1)!.n --- new_value=old_value x number

fk=fk.i i=1,…,n n:the number whose factorial to be computed

clc
clear all

fk=1;
n=input('Faktöriyeli hesaplanacak sayı= ');

for i=1:n
fk=fk*i;
% disp([num2str(i),' adımda fk değeri ',num2str(i),...
% '!= ',num2str(fk)])
end
fprintf('\n\n')
disp([num2str(n), '!= ', num2str(fk)])

Faktöriyeli hesaplanacak sayı= 5

5!= 120
>>

clc
clear all

fk=1;
n=input('Faktöriyeli hesaplanacak sayı= ');

2
2017-18 Spring DERS 8

for i=1:n
fk=fk*i;
disp([num2str(i),' adımda fk değeri ',num2str(i),...
'!= ',num2str(fk)])
end
fprintf('\n\n')
disp([num2str(n), '!= ', num2str(fk)])

Faktöriyeli hesaplanacak sayı= 5


1 adımda fk değeri 1!= 1
2 adımda fk değeri 2!= 2
3 adımda fk değeri 3!= 6
4 adımda fk değeri 4!= 24
5 adımda fk değeri 5!= 120

5!= 120
>>

MATLAB Factorial Function


Matlab has built-in functions for all mathematics functions. We will
introduce them by the content of the lectures. Some of them were the
trigonometric functions. Today we will see factorials and related functions.

f = factorial(n) returns the product of all positive integers less than or


equal to n, where n is a nonnegative integer value. If n is an array,
then f contains the factorial of each value of n. The data type and size of f is
the same as that of n.
The factorial of n is commonly written in math notation using the
exclamation point character as n!. Note that n! is not a valid
MATLAB® syntax for calculating the factorial of n.

>> factorial(5) >> factorial(10) >> factorial(6)

ans = ans = ans =

120 3628800 720

>> >> >>

Ex1:

3
2017-18 Spring DERS 8

10!
f = factorial(10)
f = 3628800

Ex2:

22!
format long
f = factorial(22)
f=
1.124000727777608e+21

In this case, f is accurate up to 15 digits, 1.12400072777760e+21,


because double-precision numbers are only accurate up to 15 digits.
Reset the output format to the default.

Factorial of Array Elements

n = [0 1 2; 3 4 5];
f = factorial(n)
f=

1 1 2
6 24 120

Vector operations

In many cases a for-loop can be replaced by an operation on a vector. This


is generally more efficient and also results in briefer code.
Two very useful commands are sum which calculates the sum of the
elements in a vector, and prod which calculates the product of the elements
in a vector.
Use the sum function to calculate the average of the values in a vector x.
The average is the sum of all the values divided by the number of values.
>> sum(x)/length(x)

Use the prod function to calculate n!.


Check the values of 6!, 1! and 0!
[1:n] is a (row) vector with elements 1, 2, 3, ..., n.
The factorial n! is the product of these elements.
The product of an empty matrix [1:0] defaults to 1, agreeing with the
convention 0! = 1.
>> prod(1:n)
>> prod(1:0)

Warnings
• If the argument of the of the sum or prod function is a matrix, then
the sum or product is taken over each column.
4
2017-18 Spring DERS 8

Apply the MATLAB functions sum and prod to the matrix


A = [1 2 3; 4 5 6]
sum calculates the sum of each column producing the row vector [5 7 9]
prod calculates the product of each column producing the row vector
[4 10 18]
>> A = [1 2 3; 4 5 6]
>> sum(A)
>> prod(A)
Use help sum or help prod to get more information.
• Remember to use semicolons ; to suppress unwanted output during
the for-loop.

Self-test Exercise
Write a MATLAB for-loop to calculate the first 20 Fibonacci numbers: F 1 =
1; F 2 = 1;, F n = F n-1 + F n-2 for n = 3,...,20, storing the results in a vector
F.

Answer:
F(1)= 1; F(2) = 1;
for n = 3:20
F(n) = F(n-1) + F(n-2);
end
Use the mouse to select the text between the word "Answer" and here to
see the answer.
Summary
MATLAB uses for loops to execute a group of statements several times.
Often a for loop can be replace by a vector operation.

Problem: Taylor expansion of a sin(x) function for every x value is given


as;

𝑥𝑥 3 𝑥𝑥 5 𝑥𝑥 7 𝑥𝑥 9 𝑥𝑥11 (−1)𝑛𝑛 𝑥𝑥 2𝑛𝑛+1
sin(𝑥𝑥) = 𝑥𝑥 − + − + − +⋯= �
3! 5! 7! 9! 11! (2𝑛𝑛 + 1)!
𝑛𝑛=0

Follow the steps below to write a program to calculate given problem.

a) Program asks for the angle x and the number of iterations n.

b)Use MATLAB’s factorial(x) to calculate sin(x).

c) Print out the value of each iteration steps.

d) Print out the sin(x) value from Matlab’s function and sind(x) for
comparison.

e) Run the program for 30 60 and 85.45 values of x .

5
2017-18 Spring DERS 8

f) Analyze the Workspace. You will see that all the variables are arrays of
1x1 .

clear
clc
x = input('Açı değeri (derece) (x): ' );
n = input('İterasyon sayısı (n): ' );

fprintf('sind(x) ---> %f\n',sind(x))


x=x*pi/180; %derece radyana çevrildi
fprintf('sin(x) ---> %f\n\n',sin(x))
top=0;
for i = 0:n
y =(-1)^i*x^(2*i+1)/factorial(2*i+1);
top=top+y;
fprintf('i=%d y=%f top=%f\n',i,y,top)
end

fprintf('\n%d adımda sin(x) değeri %f dir\n',n+1,top)

Açı değeri (derece) (x): 30


İterasyon sayısı (n): 5
sind(x) ---> 0.500000
sin(x) ---> 0.500000

i=0 y=0.523599 top=0.523599


i=1 y=-0.023925 top=0.499674
i=2 y=0.000328 top=0.500002
i=3 y=-0.000002 top=0.500000
i=4 y=0.000000 top=0.500000
i=5 y=-0.000000 top=0.500000

6 adımda sin(x) değeri 0.500000 dir


>>

Using sum:
sum(x) gives the sum of array x.

>> x=1:2:9 >> y=1:5

x= y=

1 3 5 7 9 1 2 3 4 5

>> sum(x) >> sum(y)

ans = ans =

6
2017-18 Spring DERS 8

25 15

>> >>

Let’s write the above program by using sum(x) and writing variable y as
an array. It’s the most practical way of writing MATLAB programs. Because
in MATLAB, the variables do not need to change size.

clear
clc
x = input('Açı değeri (derece) (x): ' );
n = input('İterasyon sayısı (n): ' );

fprintf('sind(x) ---> %f\n',sind(x))


x=x*pi/180; %derece radyana çevrildi
fprintf('sin(x) ---> %f\n\n',sin(x))

a=x*pi/180;
% y = zeros(1,n);
for i = 0:n
y(i+1) = (-1)^i*x^(2*i+1)/factorial(2*i+1);
end

top=sum(y);

fprintf('\n%d adımda sin(x) değeri %f dir\n',n+1,top)

Açı değeri (derece) (x): 85.45


İterasyon sayısı (n): 5
sind(x) ---> 0.996848
sin(x) ---> 0.996848

6 adımda sin(x) değeri 0.996848 dir


>>

If you analyze Workspace, you will notice that y is an array of 1x6.

There is a warning related with y. Although we do not need to define a


size for variables, it changes the size of the variable in every calculation
which results loss of time. For this reason, defining the size of the variable
at the beginning of the program helps to run faster.
In other programming languages you need to define (like int, double) or
size ( like a[20], B[2][3]). In MATLAB for each new variable a space is

7
2017-18 Spring DERS 8

reserved in the workspace. In each iteration, the space is updated. This can
cause loss of time.
Run the program by uncommenting line 6 (% y = zeros(1,n);) as (y =
zeros(1,n);). There will not be any warning when you define the size.

Problem: Writing a program to calculate the square root by Newton


method.

Algorithm:

1. Define a variable,a, to calculate its squareroot


2. Attain half of a to x, x=a/2
3. Define how many iterations you want ?, say
4. Attain x =(x + a/x)/2 in each step and print out x .
5. Compare the result with Matlab’s built in function sqrt .

clc
clear all

a = input('karekökü alınacak sayıyı giriniz (a) :');


say = input('iterasyonun tekrar sayısını giriniz :');
x = a/2;
disp('x değişkeni a nın karekökünü temsil eder')
for i = 1:say
x = (x + a / x) / 2;
disp([num2str(i), ' adımda x değeri = ', num2str(x)])
end
fprintf( 'Matlabın hesapladığı değer = %f \n',sqrt(a))

karekökü alınacak sayıyı giriniz (a) :6


iterasyonun tekrar sayısını giriniz :5
x değişkeni a nın karekökünü temsil eder
1 adımda x değeri = 2.5
2 adımda x değeri = 2.45
3 adımda x değeri = 2.4495
4 adımda x değeri = 2.4495
5 adımda x değeri = 2.4495
Matlabın hesapladığı değer = 2.449490
>>

Run the same program by defining x as an array.

clc

8
2017-18 Spring DERS 8

clear all

a = input('karekökü alınacak sayıyı giriniz (a) :');


say = input('iterasyonun tekrar sayısını giriniz :');
x=zeros(1,say);
x(1) = a/2;
disp('x değişkeni a nın karekökünü temsil eder')
for i = 2:say
x(i) = (x(i-1) + a / x(i-1)) / 2;
disp([num2str(i), ' adımda x değeri = ', num2str(x(i))])
end
fprintf( 'Matlabın hesapladığı değer = %f \n',sqrt(a))

karekökü alınacak sayıyı giriniz (a) :6


iterasyonun tekrar sayısını giriniz :5
x değişkeni a nın karekökünü temsil eder
2 adımda x değeri = 2.5
3 adımda x değeri = 2.45
4 adımda x değeri = 2.4495
5 adımda x değeri = 2.4495
Matlabın hesapladığı değer = 2.449490
>>

continue command;

continue passes control to the next iteration of a for or while loop. It skips
any remaining statements in the body of the loop for the current iteration.
The program continues execution from the next iteration.

continue applies only to the body of the loop where it is called. In nested
loops, continue skips remaining statements only in the body of the loop in
which it occurs.

Ex-1:
clc
clear all
n=input('Beşden büyük bir sayı giriniz :');

for x=1:n
y=x^2;
if x>5, break, end
if x==2, continue, end
disp(['x= ',num2str(x),' y= ',num2str(y)])
end

9
2017-18 Spring DERS 8

disp('/////')

Beşden büyük bir sayı giriniz :10


x= 1 y= 1
x= 3 y= 9
x= 4 y= 16
x= 5 y= 25
/////
>>

Ex-2:
clc
clear all
n=input('10 dan büyük bir sayı giriniz :');

for x=1:0.5:n
y=x^2;
if x>=12, break, end
if x>=3 && x<=9, continue, end
disp(['x= ',num2str(x),' y= ',num2str(y)])
end
disp('/////')

10 dan büyük bir sayı giriniz :15


x= 1 y= 1
x= 1.5 y= 2.25
x= 2 y= 4
x= 2.5 y= 6.25
x= 9.5 y= 90.25
x= 10 y= 100
x= 10.5 y= 110.25
x= 11 y= 121
x= 11.5 y= 132.25
/////
>>

10

You might also like