2017-18 Bahar      Lecture 9
MATLAB - Functions
A function is a group of statements that together perform a task. The main
prestigious property of MATLAB is its function capability. In MATLAB,
functions are defined in separate files. The name of the file and of the
function should be the same. The function file takes some input and
produces outputs. The name of the m-file and the function name should be
the same.
!!!! Do not use Turkish characters for your function and m-file names.
What is the advantage of using functions in Matlab ?
While writing a code in Matlab, if you recursively use a method for a
calculation then you need to write that code for each calculation. So by
using functions, it gives flexibility and prevents loss of time.
For example: To define an input value X as even or odd. Is it useful to
write the script for even and odd or to write a function once and call it when
needed ?
Syntax of a function statement is −
function [out1,out2, ..., outN] = function_name(input1,input2,...,
inputN)
In the first line, the inputs and outputs should be declared. Here is an
example for 4 inputs and one output function.
Example1: Let’s write a function to calculate the distance between two
distinct points.
Uzaklik=�(𝑥𝑥1 − 𝑥𝑥2)2 + (𝑦𝑦1 − 𝑦𝑦2)2
1-We need to explain the first line of the code. We have four input
numbers and will get an output value. So we write;
      function[y]=uzaklik(x1,y1,x2,y2);
2- When you save the file, it will automatically save the file with the name
uzaklik.m (function_name.m ).
                                                                             1
                                                      2017-18 Bahar   Lecture 9
function [y]=uzaklik(x1,y1,x2,y2)
% When you save the file it will automatically save the file
%with the name uzaklik.m.
y=sqrt((x2-x1)^2+(y2-y1)^2);
If you run the function as it is, it gives an error :
>> uzaklik
Error using uzaklik (line 3)
Not enough input arguments.
>> You need to
call the function from the command window or from another m-
file.
3- You can call the function from the command window or from another m-
file.
From command window;
uzaklik(1,1,4,4) will produce you an answer.
From another m-file;
Let’s write a new m-file and save it as mesafebul1.m. When you run the
code, it will call the function uzaklik.m and calculate the asked distance
clc
clear all
% Dosyayı kaydet dediğimiz zaman sizden
% dosya adı girmeniz istenecektir.
% Dosya ismini mesafebul1.m verelim.
x1=input('x1       değerini   giriniz=');
y1=input('y1       değerini   giriniz=');
x2=input('x2       değerini   giriniz=');
y2=input('y2       değerini   giriniz=');
% fonksiyonu çağıralım
uzaklik(x1,y1,x2,y2)
x1   değerini   giriniz=1      Mesafe=�(𝑥𝑥1 − 𝑥𝑥2)2 + (𝑦𝑦1 − 𝑦𝑦2)2
y1   değerini   giriniz=1
x2   değerini   giriniz=4      Mesafe=�(1 − 4)2 + (1 − 4)2
y2   değerini   giriniz4
                               Mesafe=√9 + 9
                                                                             2
                                                2017-18 Bahar     Lecture 9
ans =
                               Mesafe=√18
     4.2426
                               Mesafe=4.2426
>>
mesafebul2.m
clc
clear all
% Bu kodun ismini mesafebul2.m verelim.
x1=input('x1       değerini   giriniz=');
y1=input('y1       değerini   giriniz=');
x2=input('x2       değerini   giriniz=');
y2=input('y2       değerini   giriniz');
% fonksiyonu çağıralım
[y]=uzaklik(x1,y1,x2,y2);
fprintf('\ny mesafesi: %g \n',y)
x1   değerini   giriniz=1
y1   değerini   giriniz=1
x2   değerini   giriniz=4
y2   değerini   giriniz4
y mesafesi: 4.24264
>>
NOTE:      In           mesafebul2.m        programme        the      line
[y]=uzaklik(x1,y1,x2,y2) communicates with the function uzaklik.m.
In this communication, the order of the parameters is important, the first
parameter should call x1, second y1, third x2 and the fourth y2.
The name of the parameters is not important. Look at mesafebul2.m.
clc
clear all
% Bu kodun ismini mesafebul2.m verelim.
x1=input('x1       değerini   giriniz=');
y1=input('y1       değerini   giriniz=');
x2=input('x2       değerini   giriniz=');
y2=input('y2       değerini   giriniz');
% fonksiyonu çağıralım
                                                                         3
                                                         2017-18 Bahar   Lecture 9
[y]=uzaklik(x1,y1,x2,y2);
fprintf('\ny mesafesi: %g \n',y)
function [w]=uzaklik(a,b,c,d)
% Dosyayı kaydet dediğimiz zaman dosya adı otomatik
% olarak uzaklik.m olacaktır.
w=sqrt((c-a)^2+(d-b)^2);
x1   değerini   giriniz=1
y1   değerini   giriniz=1
x2   değerini   giriniz=4
y2   değerini   giriniz4
y mesafesi: 4.24264
>>
Example2: This function calculates two values: The first one is the distance
between two points and the second one the value of (x1+x2)/2.
function [y,k]=uzaklik_A(x1,y1,x2,y2)
% uzaklık hesabı
y=sqrt((x2-x1)^2+(y2-y1)^2);
k=(x1+x2)/2;
clc
clear all
% Bu kodun ismini mesafebul_A.m verelim.
x1=input('x1          değerini      giriniz=');
y1=input('y1          değerini      giriniz=');
x2=input('x2          değerini      giriniz=');
y2=input('y2          değerini      giriniz');
% fonksiyonu çağıralım
[y,k]=uzaklik_A(x1,y1,x2,y2);
fprintf('\ny= %g   k= %g \n',y,k)
Example 3: Write a function to calculate the mean and the geometric mean
of n values.
         (𝑥𝑥1 +𝑥𝑥2 +⋯+𝑥𝑥𝑛𝑛 )       2+8+5       15
Mean =                         =           =        =5
                 𝑛𝑛                  3         3
                                                                                4
                                                  2017-18 Bahar    Lecture 9
                  𝑛𝑛                    3             3
Geometric_Mean= �(𝑥𝑥1 ∗ 𝑥𝑥2 ∗ … ∗ 𝑥𝑥𝑛𝑛 ) = √2 ∗ 8 ∗ 5 = √80 = 4.3088
Note: Use the values x=[2 8 5] .
clc
clear all
% Dosya ismini ortalamabul.m verelim.
n=input('Data sayısı n= ');
for i=1:n
    x(i)=input('x= ');
end
[y]=ortalama(x);
disp(['aritmetik ortalama = ',num2str(y(1))]);
disp(['geometrik ortalama = ',num2str(y(2))]);
function                       function [y]=ortalama(x)
[y]=ortalama(x)
                               n=length(x);
n=length(x);
y(1)=sum(x)/n;                 q=0; w=1;
y(2)=prod(x)^(1/n);            for i=1:n
                                   q=q+x(i);
% Not: Yukarıdaki                  w=w*x(i);
fonksiyon MATLAB’ın            end
hazır fonksiyonları            y(1)=q/n;
olan sum ve prod               y(2)=w^(1/n);
fonksiyonlarını
kullanmaktadır                 % Not: Yukarıdaki fonksiyon
                               MATLAB’ın hazır fonksiyonlarını
                               kullanmadan hazırlanmıştır.
Data sayısı n= 3
x= 2
x= 8
x= 5
aritmetik ortalama = 5
geometrik ortalama = 4.3089
>>
**** MATLAB built-in functions
                                                                          5
                                                  2017-18 Bahar     Lecture 9
mean : Verilerin ortalama değerini hesaplar yani aritmetik ortalama alır
geomean : Verilerin geometrik ortasını hesaplar
harmmean : Verilerin harmonik ortasını hesaplar
>> x=[2 8 5]
x=
       2   8   5
>> mean(x)
ans =
>> geomean(x)
ans =
   4.3089
>>
Example 4:
Addition of two matrices , topla_m.m
   function[matris] = topla_m(A,B)
1 if size(A)==size(B)
2 matris=A+B;
3 disp(matris)
4 else
5 disp('Bu Matrisler Toplanmaz!')
6 end
7
What we do with this function ?
  • Present the values of A and B matrices,
  • Use the function size and compare the size of the matrices with İf
    – Else method.
  • If the size of the matris A is equal to the size ot the matris B, then we
    sum up two matrices.
  •  If the sizes are not equal then print out that “Those matrices can not
    be summed up!!”.
  • Save the function as topla_m.m.
   •
                                                                            6
                                                    2017-18 Bahar     Lecture 9
Global Variables
Global variables can be shared by more than one function. For this, you
need to declare the variable as global in all the functions.
If you want to access that variable from the base workspace, then declare
the variable at the command line.
The global declaration must occur before the variable is actually used in a
function. It is a good practice to use capital letters for the names of global
variables to distinguish them from other variables.
Example
Let us create a function file named average.m and type the following code
in it –
function avg = average(nums)
global TOTAL
avg = sum(nums)/TOTAL;
end
Create a script file and type the following code in it −
global TOTAL;
TOTAL = 10;
n = [34, 45, 25, 45, 33, 19, 40, 34, 38, 42];
av = average(n)
When you run the file, it will display the following result −
av = 35.500
                                                                             7
                                                  2017-18 Bahar     Lecture 9
while LOOP
Tekrarlı deyimleri elde etmenin bir başka yolu “while” deyimini kullanmaktır.
Bu durumda önceden verilen bir şart sağlanmadığı sürece bir iterasyon
süreci devam eder. while komutu aşağıdaki şeklinde bir yapıya sahiptir.
      while koşul
           komutlar
           komutlar
           komutlar
      end
Soru: 1 den n’e kadar 1 er artırımla değişen sayıların toplamını while
döngüsüyle hesaplayalım:
 clc                                  n= 5
 clear all                            toplam= 15
                                      >>
 n=input('n= ');
 top=0; i=0;
 while i <= n
     top=top+i;
     i=i+1;
 end
 disp(['toplam= ',num2str(top)])
Aynı işlemi komut penceresinden while kullanmadan
hesaplayalım
>> n=1:5
n =
       1      2       3      4      5
>> sum(n)
ans =
      15
>>
Uygulama: break komutunu while döngüsünde kullanalım.
 clc                               Bir sayı giriniz : 7
 clear all                         /////
                                   /////
 n=input('Bir sayı giriniz :');    /////
 while n>=0                        *****
                                                                            8
                                                   2017-18 Bahar   Lecture 9
      n=n-1;                               >>
      if n<=3
          disp('*****')
          break
      end
      disp('/////')
end
Soru: Girilen sayının faktöryelini hesaplayalım.
 clc
 clear all
i=0; fk=1;
n=input('Bir sayı giriniz :');
while i<n
    i=i+1;
    fk=fk*i;
end
fprintf('%d nin faktöriyeli = %d\n',n,fk);
Bir sayı giriniz :5
5 nin faktöriyeli = 120
>>
Diğer bir şekilde yazalım
 clc
 clear all
i=1; fk=1;
n=input('Bir sayı giriniz :');
while i<=n
    fk=fk*i;
    i=i+1;
end
fprintf('%d nin faktöriyeli = %d\n',n,fk);
Bir sayı giriniz :5
5 nin faktöriyeli = 120
>>
Hatırlatma: aynı işlemi Matlabın hazır fonksiyonu factorial(n) kullanarak
da hesaplayabiliyorduk.
                                                                          9
                                                   2017-18 Bahar     Lecture 9
Soru: x=2 ve y=5 veriliyor. Sayıları döngü (while çevrimi) içerisinde 2 katını
alıp birbiriyle çarpınız. Bu işleme çarpım 500 den büyük olana kadar devam
ediniz. Sayıları kaç kez katlandığını hesaplayan program kodunu yazınız.
clc
clear all
x=2; y=5; sayac=0;
while x*y<500
    x=2*x;
    y=2*y;
    sayac=sayac+1;
    fprintf('sayac x y x*y = %g    %g   %g   %g\n',sayac,x,y,x*y);
end
fprintf('\n%g değerine %d denemede ulaşıldı.\n',x*y,sayac);
sayac x y x*y = 1      4 10 40
sayac x y x*y = 2      8 20 160
sayac x y x*y = 3      16 40 640
640 değerine 3 denemede ulaşıldı.
>>
% Aynı programı şu şekilde de yazabiliriz.
clc
clear all
x=2; y=5; sayac=0;
k=x*y;
while k<500
    x=2*x;
    y=2*y;
    k=x*y;
    sayac=sayac+1;
    fprintf('sayac x y x*y = %g    %g   %g   %g\n',sayac,x,y,x*y);
end
fprintf('\n%g değerine %d denemede ulaşıldı.\n',x*y,sayac);
Sonsuz döngü: Sonsuz döngüde koşul sürekli doğrudur. Programdan
break komutuyla veya özel bir şartın sağlanmasıyla çıkılır.
while komutunda koşul yerine 1 veya true yazmak sonsuz döngü
oluşturur.
while 1                                while true
    komutlar                               komutlar
    komutlar                               komutlar
end                                    end
                                                                            10
                                                  2017-18 Bahar    Lecture 9
MATLAB Hazır Fonksiyonlarına Devam:
Matlab da bölme işlemi sonucu kalan bulma işlemi iki şekilde yapılır:
mod(x,y) : x/y bölme işleminde işaretli kalanı verir. (Modül)
rem(x,y) : x/y bölme işleminde işaretsiz kalanı verir.
clc
clear all
while 1
    x=input('Bir sayı giriniz :');
    if mod(x,2)==0
         disp('Girilen sayı çifttir')
    else
         disp('Girilen sayı tektir')
    end
end
Bir sayı giriniz :4
Girilen sayı çifttir
Bir sayı giriniz :5
Girilen sayı tektir
Bir sayı giriniz :7
Girilen sayı tektir
Bir sayı giriniz :9
Girilen sayı tektir
Bir sayı giriniz :0
Girilen sayı çifttir
Bir sayı giriniz :-9
Girilen sayı tektir
Bir sayı giriniz :-4
Girilen sayı çifttir
Bir sayı giriniz :
Uygulama: mod ve rem uygulaması – Bu uygulama bilgilendirme amaçlıdır.
clc
clear all
disp('x/y işleminde kalan değeri bulma')
while 1
    x=input('x değerini giriniz: ');
    y=input('y değerini giriniz: ');
    fprintf('mod(x,y) x/y işleminde kalan değer %g\n',mod(x,y))
    fprintf('rem(x,y) x/y işleminde kalan değer %g\n\n',rem(x,y))
end
x/y işleminde kalan değeri bulma
x değerini giriniz: 11
y değerini giriniz: 7
                                                                         11
                                                  2017-18 Bahar    Lecture 9
mod(x,y) x/y işleminde kalan değer 4
rem(x,y) x/y işleminde kalan değer 4
x değerini giriniz: 11
y değerini giriniz: 9
mod(x,y) x/y işleminde kalan değer 2
rem(x,y) x/y işleminde kalan değer 2
x değerini giriniz: -11
y değerini giriniz: 9
mod(x,y) x/y işleminde kalan değer 7
rem(x,y) x/y işleminde kalan değer -2
x değerini giriniz:
Soru: Yazacağınız program kullanıcı -99 girene kadar, 0<x<100 aralığında
girilen sayıları toplam değişkenine eklesin ve en son toplam değerini ekrana
yazsın.
clc
clear all
toplam=0;
display('Programı bitirmek için -99 giriniz')
while 1
    x=input('Bir sayı giriniz :');
    if x==-99, break, end
    if x<=0 || x>=100
        disp('Değer 0 - 100 arası olmalı!!!')
        continue;
    end
    toplam=toplam+x;
end
fprintf('Toplam = %g\n',toplam);
Programı bitirmek için -99 giriniz
Bir sayı giriniz :5
Bir sayı giriniz :25
Bir sayı giriniz :120
Değer 0 - 100 arası olmalı!!!
Bir sayı giriniz :6
Bir sayı giriniz :-99
Toplam = 36
>>
                                                                          12
                                                  2017-18 Bahar   Lecture 9
Aynı soruyu farklı bir program koduyla çözelim.
 clc
 clear all
toplam=0;
display('Programı bitirmek için -99 giriniz')
while 1
    x=input('Bir sayı giriniz :');
    if x==-99, break, end
    if x>0 && x<100
         toplam=toplam+x;
    else
         disp('Değer 0 - 100 arası olmalı!!!')
    end
end
fprintf('Toplam = %g\n',toplam);
Programı bitirmek için -99 giriniz
Bir sayı giriniz :50
Bir sayı giriniz :20
Bir sayı giriniz :-9
Değer 0 - 100 arası olmalı!!!
Bir sayı giriniz :15
Bir sayı giriniz :120
Değer 0 - 100 arası olmalı!!!
Bir sayı giriniz :-99
Toplam = 85
>>
Uygulama: Sonsuz döngüyle ilgili uygulama örneği
clc
clear all
y=0;
while 1
    y=y+1;   % y=y+2 ve y=y+3
    disp([num2str(y)]) % if mod(y,100)==0, disp([num2str(y)]),
end;
    if y==100000, break, end; % y==1000000000
end
fprintf('\n\n\n///// y= %g\n',y)
                                                                        13