SlideShare a Scribd company logo
1 of 73
Download to read offline
Bab 1 Pendahuluan
MATLAB berasal dari kata Matrix Laboratory. Versi pertamanya ditulis di University of New
Mexico dan Stanford University pada akhir tahun 70-an, dimaksudkan untuk memecahkan
permasalahan di teori matriks, aljabar linier, dan analisa numerik. Sebelumnya telah dikenal
program-program LINPACK DAN EISPACK, yang dikemas dalam FORTRAN untuk
perhitungan matriks.
MATLAB yang saat ini digunakan kemampuannya melampaui Matrix Laboratory yang
sebenarnya. MATLAB adalah bahasa pemrograman tingkat tinggi untuk perhitungan
teknik. Isinya mencakup perhitungan, visualisasi, dan pemrograman dalam lingkungan yang
mudah digunakan dimana masalah dan solusinya ditampilkan dalam notasi matematika yang
sudah dikenal. Fungsi-fungsinya meliputi :
Matematika dan komputasi
Pengembangan Algoritma
Modelling, simulasi, dan pembuatan proto-type
Analisa data, eksplorasi, dan visualisasi
Ilmu pengetahuan dan grafik teknik,
Pengembangan aplikasi, termasuk pembuatan antarmuka pengguna secara
grafis.
MATLAB terus berkembang dari tahun ke tahun dengan berbagai masukan dari para
pengguna MATLAB. Versi Matlab meliputi hal-hal yang terkait di setiap bagian MATLAB
dari deret matematika dan konstruksi bahasa pemrograman, sampai stuktur data dan
metoda-metoda orientasi objek, untuk visualisasi dan perlengkapan pembuatan GUI
MATLAB adalah suatu lingkungan dan bahasa pemrograman , dan satu dari kelebihannya
ada kenyataan bahwa bahasa MATLAB memungkinan kita untuk membuat peralatan yang
bisa dipakai ulang. Fungsi-fungsi dan program-program khusus dapat ditulis secara mudah
di dalam kode MATLAB. Sebagaimana fungsi-fungsi MATLAB terus ditulis untuk
memecahkan masalah-masalah tertentu, tentu diperlukan meng-kelompokan fungsi-fungsi
yang berhubungan menjadi satu direktori. Hal ini adalah konsep dasar dari Toolbox:
kumpulan khusus dari M-file untuk bekerja pada masalah-masalah tertentu.
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
2
Penggunaan M-files dalam Matlab
Ada perbedaan penggunaan Matlab di dalam platform yang berbeda :
Macintosh
Terdapat sebuah built-in editor untuk m-files; pilih "New M-file" dari menu File. Editor
lainnya juga dapat digunakan (tapi pastikan ahwa file telah disave dalam format text, dan
dapat diload bila akan mulai menggunakan Matlab).
Windows
Menggunakan Matlab dalam Windows serupa dengan cara menggunakannya di dalam
Macintosh. Akan tetapi, perlu diketahui bahwa m-file akan disimpan di dalam clipboard.
Karenanya, perlu dipastikan bahwa m-file telah disimpan sebagai namafile.m .
Unix
Di dalam unix, editor dijalankan secara terpisah dari Matlab. Cara terbaik adalah dengan
membuat sebuah direktori untuk semua m-files, kemudian cd ke direktori yang dimaksud
sebelum menjalankan Matlab maupun editor. Untuk mulai menggunakan Matlab dari
window Xterm hanya perlu dengan mengetikkan : matlab.
Perintah juga dapat diketikkan langsung ke dalam matlab, atau taruh semua dari perintah
yang diperlukan untuk bersama-sama di dalam sebuah an m-file, dan hanya jalankan file.
Bila semua m-files diletakkan dalam directory yang sama dengan direktori tempat matlab
dijalankan, maka matlab akan selalu menjalankannya.
Menu help dalam Matlab
Matlab memberikan menu help dengan cukup mengetikkan :
help commandname
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
3
Pengertian m-file
Sebuah m-file atau file script, adalah file teks yang sederhana yang berisi perintah Matlab. Bila file
ini dijalankan, Matlab membaca command ini dan mengeksekusinya sebagaimana bila setiap
command diketik langsung pada prompt Matlab. Semua m-file memiliki ekstensi “. m”. Bila sebuah
m-file baru dibuat dengan nama yang sama dengan yang telah ada di m-file yang sudah ada, Matlab
akan memilih m-file yang lebih dahulu berada di urutan path. Untuk itu, buatlah m-file dengan
nama yang belum ada di default Matlab, bisa dicoba dengan diberi nama dalam bahasa Indonesia.
Untuk mengetahui file mana yang sudah ada, ketik help filename pada prompt Matlab
Alasan Menggunakan m-file
Untuk permasalahan yang sederhana, mengetikkan perintah langsung pada prompt Matlab adalah
hal yang mudah, akan tetapi, jumlah baris dari command makin lama makin banyak, dan bila sedang
melakukan suatu percobaan, maka bila harus mengetikkannya berkali-kali adalah hal yang sia-sia.
Dalam hal ini, m-file dapat membantu, bahkan penting untuk menghindar dari masalah ini.
Cara Menjalankan m-file
Setela m-file disimpan dengan nama *.m pada folder Matlab, atau direktori, file ini dapat dieksekusi
hanya dengan mengetikkan nama file pada prompt Matlab
Cara Membuat m-file
Untuk membuat M-file pada PC, pilih New dari File menu dan pilih M-file. Prosedur ini akan
menampilkan text editor window dimana perintah-perintah MATLAB dapat diberikan.. Tampilan
berikut menunjukkan perintah yang dikirimkan melalui file skrip.
% Contoh.m file skrip untuk masalah acid water bath
initial_con=90
min_con=50
lost=0.01;
n=floor(log2(initial_con/min_con)/log2(1+lost))
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
4
File ini disimpan sebagai M-file contoh.m pada disket dengan memilih Save dari menu File,
kemudian MATLAB akan menjalankan perintah dari contoh.m pada saat contoh diketikkan pada
prompt MATLAB:
Dikarenakan perlengkapan dari file skrip, MATLAB melengkapi beberapa fungsi yang berguna bila
digunakan di dalam M-file, yaitu :
Perintah Arti
disp(ans)
menampilkan hasil tanpa mengindentifikasi nama
variabel
echo
mengendalikan command window mengulang
perintah-perintah pada file skrip
input prompt buatan untuk masukan
keyboard
memberikan kendali pada keyboard secara temporary
(ketik return untuk keluar)
pause berhenti sampai sembarang tombol keyboard ditekan
pause(n) berhenti untuk n detik
waitforbuttonp
ress
berhenti sampai pemakai menekan tombol mouse atau
key keyboard
Contoh :
% Contoh.m file skrip untuk masalah acid water bath
initial_con=90
min_con=50
lost=input(‘Masukkan persentasi kehilangan dengan setiap dip >’)/100
n=floor(log2(initial_con/min_con)/log2(1+lost))
EDU>>contoh
initial_con=
90
min_con=
50
n =
59
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
5
Hasil file skrip :
Contoh :
Hasil :
echo on
% Contoh.m file skrip untuk masalah acid water bath
initial_con=90
min_con=50
lost=input(‘Masukkan persentasi kehilangan dengan setiap dip >’)/100
n=floor(log2(initial_con/min_con)/log2(1+lost))
echo off
EDU>> contoh
% Contoh.m file skrip untuk masalah acid water bath
initial_con=90
initial_con =
90
min_con=50
min_con =
50
lost=input(‘Masukkan persentasi kehilangan dengan setiap
dip >’)/100
Masukkan persentasi kehilangan dengan setiap dip > 20
lost =
0.2
n=floor(log2(initial_con/min_con)/log2(1+lost))
n =
3
echo off
Masukkan persentasi kehilangan dengan setiap dip > 5
lost =
0.05
n =
12
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
6
Tutorial Dasar Matlab
Matlab adalah program interaktif untuk komputasi numeric dan visualisasi data yang umum
digunakan oleh ilmuwan kendali untuk analisa dan perancangan. Ada berbagai toolbox yang
berbeda yang dapat digunakan untuk berbagai area aplikasi yang berbeda. Untuk diktat ini, hanya
penggunaan pada bidang sistem kendali yang akan dibahas.
Vektor
Sebagai permulaan, matlab akan digunakan untuk suatu permasalahan yang sederhana seperti
vector. Setiap elemen dari vector akan disusun dengan dipisahkan oleh space di dalam tanda
kurung. Sebagai contoh, dapat diketik seperti berikut ini pada command window dari program
matlab :
Matlab akan kembali menuliskan :
Untuk menyusun deret bilangan dari 0 sampai dengan 20 dengan jarak 2 maka diketikkan :
Untuk memanipulasi vector dengan menambahkan dua kepada setiap elemen dari vector a, maka
persamaannya adalah :
a =
1 2 3 4 5 6 9 8 7
a = [1 2 3 4 5 6 9 8 7]
t = 0:2:20
t =
0 2 4 6 8 10 12 14 16 18 20
b = a + 2
b =
3 4 5 6 7 8 11 10 9
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
7
Bila kedua vector, yaitu a dan b akan ditambahkan,
dan seterusnya
c = a + b
c =
4 6 8 10 12 14 20 18 16
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
8
Fungsi-Fungsi Matlab
Matlab telah menyediakan beberapa fungsi standar. Setiap fungsi adalah satu blok kode yang
mengerjakan tugas tertentu. Pada matlab telah meliputi fungsi-fungsi standar yaitu : sin, cos, log,
exp, sqrt, dan sebagainya. Biasanya, konstanta seperti pi, and i or j untuk akar dari -1, juga telah
termasuk dalam Matlab.
Untuk mengetahui fungsi dari fungsi-fungsi yang ada, ketikkan :
help [function name] pada Matlab command window.
Saat menuliskan perintah seperti roots, plot, atau step ke dalam Matlab, sebenarnya yang sedang
dilakukan adalah menjalankan sebuah m-file dengan masukan dan keluaran yang telah ditulis untuk
memenuhi tugas tertentu. Jenis m-file ini serupa dengan subrutin dalam bahasa pemrograman yang
memiliki masukkan (parameter yang telah dimasukkan ke dalam m-file), keluaran (nilai yang
diperoleh dari m-file), dan satu badan perintah-perintah yang berisi variabel local. Matlab menyebu
m-file ini sebagai function (fungsi). Untuk itu, sebuah perintah function dapat ditulis baru, sesuai
tujuan, artinya, sebuah toolbox baru dapat disusun.
Fungsi baru adalah sebuah m-file dan memiliki ekstensi file “. m”. File ini disimpan pada direktori
yang sama dengan software Matlab, atau di dalam direktori yang berisi path yang diacu oleh Matlab.
Baris pertama sebuah function haruslah berikut ini :
function [output1,output2] = filename(input1,input2,input3)
Sebuah fungsi dapat menerima input dan mengeluarkan output dengan jumlah variabel sebanyak
yang diperlukan. Baris yang merupakan sebuah keterangan untuk memudahkan pembacaan
program biasa diberikan tanda “%” pada awal tiap baris.
sin(pi/4)
ans =
0.7071
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
9
Fungsi dapat ditulis dengan trik, dan praktis diperlukan untuk keberhasilan menuliskan sebuah
fungsi untuk mendapatkan hasil yang diperlukan. Contoh berikut adalah m-file yaitu add.m yang
berisi :
Bila ketiga baris perintah ini diberi nama add.m pada direktori Matlab, maka pada file ini dapat
dieksekusi pada command line :
Polynomials
Pada Matlab, sebuah polynomial ditampilkan dengan sebuah vector. Untuk menuliskan sebuah
polynomial di dalam matlab dapat dilihat contoh berikut ini :
Persamaan :
Dalam Matlab ditulis :
Matlab dapat mengartikan sebuah vector sepanjang n+1 sebagai deret polynomial sepanjang n.
Untuk itu, dapat dilakukan dengan :
dipresentasikan dalam Matlab sebagai :
y = [1 0 0 0 1]
function [var3] = add(var1,var2)
%add is a function that adds two numbers
var3 = var1+var2;
y = add(3,8)
x = [1 3 -15 -2 9]
x =
1 3 -15 -2 9
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
10
Pada polynomial dengan s=2,
z = polyval([1 0 0 0 1],2)
z =
17
Untuk mencari akar persamaan dari :
adalah dengan menuliskan :
Untuk mengkalikan dua polynomial :
Contoh :
Untuk membagi dua polynomial :
roots([1 3 -15 -2 9])
ans =
-5.5745
2.5836
-0.7951
0.7860
x = [1 2];
y = [1 4 8];
z = conv(x,y)
z =
1 6 16 16
[xx, R] = deconv(z,y)
xx =
1 2
R =
0 0 0 0
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
11
Sebagaimana dapat dilihat, bila untuk menjumlahkan dua polynomial, dengan panjang yang sama,
dapat digunakan perintah polyadd, yang sudah dijadikan fungsi di dalam mfile :
Matrik
Entering matrices into Matlab is the same as entering a vector, except each row of elements is
separated by a semicolon (;) or a return:
B = [1 2 3 4;5 6 7 8;9 10 11 12]
B =
1 2 3 4
5 6 7 8
9 10 11 12
B = [ 1 2 3 4
5 6 7 8
9 10 11 12]
B =
1 2 3 4
5 6 7 8
9 10 11 12
Matrices in Matlab can be manipulated in many ways. For one, you can find the
transpose of a matrix using the apostrophe key:
C = B'
z = polyadd(x,y)
x =
1 2
y =
1 4 8
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
12
C =
1 5 9
2 6 10
3 7 11
4 8 12
It should be noted that if C had been complex, the apostrophe would have actually
given the complex conjugate transpose. To get the transpose, use .' (the two
commands are the same if the matix is not complex).
Now you can multiply the two matrices B and C together. Remember that order
matters when multiplying matrices.
D = B * C
D =
30 70 110
70 174 278
110 278 446
D = C * B
D =
107 122 137 152
122 140 158 176
137 158 179 200
152 176 200 224
Another option for matrix manipulation is that you can multiply the corresponding
elements of two matrices using the .* operator (the matrices must be the same size
to do this).
E = [1 2;3 4]
F = [2 3;4 5]
G = E .* F
E =
1 2
3 4
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
13
F =
2 3
4 5
G =
2 6
12 20
If you have a square matrix, like E, you can also multiply it by itself as many
times as you like by raising it to a given power.
E^3
ans =
37 54
81 118
If wanted to cube each element in the matrix, just use the element-by-element
cubing.
E.^3
ans =
1 8
27 64
You can also find the inverse of a matrix:
X = inv(E)
X =
-2.0000 1.0000
1.5000 -0.5000
or its eigenvalues:
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
14
eig(E)
ans =
-0.3723
5.3723
There is even a function to find the coefficients of the characteristic polynomial of a
matrix. The "poly" function creates a vector that includes the coefficients of the
characteristic polynomial.
p = poly(E)
p =
1.0000 -5.0000 -2.0000
Remember that the eigenvalues of a matrix are the same as the roots of its
characteristic polynomial:
roots(p)
ans =
5.3723
-0.3723
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
15
Plotting in Matlab
Plotting
Menggambarkan plotting pada matlab dapat dilakukan dengan mudah. Bila sebuah gelombang sinus
akan diplot sesuai fungsi waktu, maka pertama-tama akan dibuat vector waktu (dengan memberikan
tanda titik koma, sebagai tanda bahwa tidak semua nilai ditampilkan), maka matlab akan
menggambarkan keluarannya.
Contoh :
One of the most important functions in Matlab is the plot function. Plot also happens
to be one of the easiest functions to learn how to use. The basic format of the
function is to enter the following command in the Matlab command window or into a
m-file.
plot(x,y)
t=0:0.25:7;
y = sin(t);
plot(t,y)
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
16
This command will plot the elements of vector x on the horizontal axis of a figure,
and the elements of the vector y on the vertical axis of the figure. The default is that
each time the plot command is issued, the current figure will be erased; we will
discuss how to override this below. If we wanted to plot the simple, linear formula:
y=3x
We could create a m-file with the following lines of code:
x = 0:0.1:100;
y = 3*x;
plot(x,y)
which will generate the following plot,
One thing to keep in mind when using the plot command is that the vectors x and y
must be the same length. The other dimension can vary. Matlab can plot a 1 x n
vector versus a n x 1 vector, or a 1 x n vector versus a 2 x n matrix (you will get two
lines), as long as n is the same for both vectors.
The plot command can also be used with just one input vector. In that case the
vector columns are plotted versus their indices (the vector 1:1:n will be used for the
horizontal axis). If the input vector contains complex numbers, Matlab plots the real
part of each element (on the x-axis) versus the imaginary part (on the y-axis).
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
17
Plot aesthetics
The color and point marker can be changed on a plot by adding a third parameter (in
single quotes) to the plot command. For example, to plot the above function as a
red, dotted line, the m-file should be changed to:
x = 0:0.1:100;
y = 3*x;
plot(x,y,'r:')
The plot now looks like:
The third input consists of one to three characters which specify a color and/or a
point marker type. The list of colors and point markers is as follows:
y yellow . point
m magenta o circle
c cyan x x-mark
r red + plus
g green - solid
b blue * star
w white : dotted
k black -. dashdot
-- dashed
You can plot more than one function on the same figure. Let's say you want to plot a
sine wave and cosine wave on the same set of axes, using a different color and point
marker for each. The following m-file could be used to do this:
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
18
x = linspace(0,2*pi,50);
y = sin(x);
z = cos(x);
plot(x,y,'r', x,z,'gx')
You will get the following plot of a sine wave and cosine wave, with the sine wave in a
solid red line and the cosine wave in a green line made up of x's:
By adding more sets of parameters to plot, you can plot as many different functions on
the same figure as you want. When plotting many things on the same graph it is useful
to differentiate the different functions based on color and point marker. This same effect
can also be achieved using the hold on and hold off commands. The same plot
shown above could be generated using the following m-file:
x = linspace(0,2*pi,50);
y = sin(x);
plot(x,y,'r')
z = cos(x);
hold on
plot(x,z,'gx')
hold off
Always remember that if you use the hold on command, all plots from then on will be
generated on one set of axes, without erasing the previous plot, until the hold off
command is issued.
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
19
Subplotting
More than one plot can be put on the same figure using the subplot command. The
subplot command allows you to separate the figure into as many plots as desired, and
put them all in one figure. To use this command, the following line of code is entered
into the Matlab command window or an m-file:
subplot(m,n,p)
This command splits the figure into a matrix of m rows and n columns, thereby creating
m*n plots on one figure. The p'th plot is selected as the currently active plot. For
instance, suppose you want to see a sine wave, cosine wave, and tangent wave plotted
on the same figure, but not on the same axis. The following m-file will accomplish this:
x = linspace(0,2*pi,50);
y = sin(x);
z = cos(x);
w = tan(x);
subplot(2,2,1)
plot(x,y)
subplot(2,2,2)
plot(x,z)
subplot(2,2,3)
plot(x,w)
As you can see, there are only three plots, even though I created a 2 x 2 matrix of 4
subplots. I did this to show that you do not have to fill all of the subplots you have
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
20
created, but Matlab will leave a spot for every position in the matrix. I could have easily
made another plot using the line subplot(2,2,4) command. The subplots are arranged
in the same manner as you would read a book. The first subplot is in the top left corner,
the next is to its right. When all the columns in that row are filled, the left-most column
on the next row down is filled (all of this assuming you fill your subplots in order i.e. 1,
2, 3,..).
One thing to note about the subplot command is that every plot command issued later
will place the plot in whichever subplot position was last used, erasing the plot that was
previously in it. For example, in the m-file above, if a plot command was issued later in
the m-file, it would be plotted in the third position in the subplot, erasing the tangent
plot. To solve this problem, the figure should be cleared (using clf), or a new figure
should be specified (using figure).
Changing the axis
Now that you have found different ways to plot functions, you can customize your plots
to meet your needs. The most important way to do this is with the axis command. The
axis command changes the axis of the plot shown, so only the part of the axis that is
desirable is displayed. The axis command is used by entering the following command
right after the plot command (or any command that has a plot as an output):
axis([xmin, xmax, ymin, ymax])
For instance, suppose want to look at a plot of the function y=exp(5t)-1. If you enter the
following into Matlab
t=0:0.01:5;
y=exp(5*t)-1;
plot(t,y)
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
21
you should have the following plot:
As you can see, the plot goes to infinity. Looking at the y-axis (scale: 8e10), it is
apparent that not much can be seen from this plot. To get a better idea of what is going
on in this plot, let's look at the first second of this function. Enter the following
command into the Matlab command window.
axis([0, 1, 0, 50])
and you should get the following plot:
Now this plot is much more useful. You can see more clearly what is going on as the
function moves toward infinity. You can customize the axis to your needs. When using
the subplot command, the axis can be changed for each subplot by issuing an axis
command before the next subplot command. There are more uses of the axis command
which you can see if you type help axis in the Matlab command window.
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
22
Adding text
Another thing that may be important for your plots is labeling. You can give your plot a
title (with the title command), x-axis label (with the xlabel command), y-axis label
(with the ylabel command), and put text on the actual plot. All of the above commands
are issued after the actual plot command has been issued.
A title will be placed, centered, above the plot with the command: title('title
string'). The x-axis label is issued with the following command: xlabel('x-axis
string'). The y-axis label is issued with the following command: ylabel('y-axis
string').
Furthermore, text can be put on the plot itself in one of two ways: the text command
and the gtext command. The first command involves knowing the coordinates of
where you want the text string. The command is text(xcor,ycor,'textstring'). To
use the other command, you do not need to know the exact coordinates. The command
is gtext('textstring'), and then you just move the cross-hair to the desired location
with the mouse, and click on the position you want the text placed.
To further demonstrate labeling, take the step response plot from above. Assuming that
you have already changed the axis, copying the following lines of text after the axis
command will put all the labels on the plot:
title('step response of something')
xlabel('time (sec)')
ylabel('position, velocity, or something like that')
gtext('unnecessary labeling')
The text "unnecessary labeling" was placed right above the position, I clicked on. The
plot should look like the following:
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
23
Other commands that can be used with the plot command are:
• clf (clears the current plot, so it is blank)
• figure (opens a new figure to plot on, so the previous figure is saved)
• close (closes the current figure window)
• loglog (same as plot, except both axes are log base 10 scale)
• semilogx (same as plot, except x-axis is log base 10 scale)
• semilogy (same as plot, except y-axis is log base 10 scale)
• grid (adds grid line to your plot)
Of course this is not a complete account of plotting with Matlab, but it should give you
a nice start
Printing
Printing in Matlab is pretty easy. Just follow the steps illustrated below:
Macintosh
To print a plot or a m-file from a Macintosh, just click on the plot or m-file, select
Print under the File menu, and hit return.
Windows
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
24
To print a plot or a m-file from a computer running Windows, just selct Print from
the File menu in the window of the plot or m-file, and hit return.
Unix
To print a plot on a Unix workstation enter the command:
print -P<printername>
If you want to save the plot and print it later, enter the command:
print plot.ps
Sometime later, you could print the plot using the command "lpr -P plot.ps" If
you are using a HP workstation to print, you would instead use the command
"lpr -d plot.ps"
To print a m-file, just print it the way you would any other file, using the
command "lpr -P <name of m-file>.m" If you are using a HP workstation to
print, you would instead use the command "lpr -d plot.ps<name of m-file>.m"
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
25
Matlab Commands List
The following list of commands can be very useful for future reference. Use "help" in
Matlab for more information on how to use the commands.
In these tutorials, we use commands both from Matlab and from the Control Systems
Toolbox, as well as some commands/functions which we wrote ourselves. For those
commands/functions which are not standard in Matlab, we give links to their descriptions.
For more information on writing Matlab functions, see the function page.
Note:Matlab commands from the control system toolbox are highlighted in red.
Non-standard Matlab commands are highlighted in green.
Command Description
abs Absolute value
acker Compute the K matrix to place the poles of A-BK, see also place
axis Set the scale of the current plot, see also plot, figure
bode Draw the Bode plot, see also logspace, margin, nyquist1
c2dm Continuous system to discrete system
clf Clear figure (use clg in Matlab 3.5)
conv Convolution (useful for multiplying polynomials), see also deconv
ctrb The controllability matrix, see also obsv
deconv Deconvolution and polynomial division, see also conv
det Find the determinant of a matrix
dimpulse Impulse response of discrete-time linear systems, see also dstep
dlqr
Linear-quadratic requlator design for discrete-time systems, see also
lqr
dlsim Simulation of discrete-time linear systems, see also lsim
dstep Step response of discrete-time linear systems, see also stairs
eig Compute the eigenvalues of a matrix
eps Matlab's numerical tolerance
feedback Feedback connection of two systems.
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
26
figure
Create a new figure or redefine the current figure, see also subplot,
axis
for For, next loop
format Number format (significant digits, exponents)
function Creates function m-files
grid Draw the grid lines on the current plot
gtext Add a piece of text to the current plot, see also text
help HELP!
hold Hold the current graph, see also figure
if Conditionally execute statements
imag Returns the imaginary part of a complex number, see also real
impulse
Impulse response of continuous-time linear systems, see also step,
lsim, dlsim
input Prompt for user input
inv Find the inverse of a matrix
jgrid
Generate grid lines of constant damping ratio (zeta) and settling time
(sigma), see also sgrid, sigrid, zgrid
legend Graph legend
length Length of a vector, see also size
linspace Returns a linearly spaced vector
lnyquist1 Produce a Nyquist plot on a logarithmic scale, see also nyquist1
log natural logarithm, also log10: common logarithm
loglog Plot using log-log scale, also semilogx/semilogy
logspace Returns a logarithmically spaced vector
lqr
Linear quadratic regulator design for continuous systems, see also
dlqr
lsim Simulate a linear system, see also step, impulse, dlsim.
margin
Returns the gain margin, phase margin, and crossover frequencies,
see also bode
norm Norm of a vector
nyquist1 Draw the Nyquist plot, see also lnyquist1. Note this command was
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
27
written to replace the Matlab standard command nyquist to get more
accurate Nyquist plots.
obsv The observability matrix, see also ctrb
ones Returns a vector or matrix of ones, see also zeros
place Compute the K matrix to place the poles of A-BK, see also acker
plot Draw a plot, see also figure, axis, subplot.
poly Returns the characteristic polynomial
polyadd Add two different polynomials
polyval Polynomial evaluation
print Print the current plot (to a printer or postscript file)
pzmap Pole-zero map of linear systems
rank
Find the number of linearly independent rows or columns of a
matrix
real Returns the real part of a complex number, see also imag
rlocfind Find the value of k and the poles at the selected point
rlocus Draw the root locus
roots Find the roots of a polynomial
rscale Find the scale factor for a full-state feedback system
set
Set(gca,'Xtick',xticks,'Ytick',yticks) to control the number and
spacing of tick marks on the axes
series Series interconnection of Linear time-independent systems
sgrid
Generate grid lines of constant damping ratio (zeta) and natural
frequency (Wn), see also jgrid, sigrid, zgrid
sigrid
Generate grid lines of constant settling time (sigma), see also jgrid,
sgrid, zgrid
size Gives the dimension of a vector or matrix, see also length
sqrt Square root
ss
Create state-space models or convert LTI model to state space, see
also tf
ss2tf State-space to transfer function representation, see also tf2ss
ss2zp State-space to pole-zero representation, see also zp2ss
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
28
stairs Stairstep plot for discreste response, see also dstep
step Plot the step response, see also impulse, lsim, dlsim.
subplot Divide the plot window up into pieces, see also plot, figure
text
Add a piece of text to the current plot, see also title, xlabel, ylabel,
gtext
tf
Creation of transfer functions or conversion to transfer function, see
also ss
tf2ss Transfer function to state-space representation, see also ss2tf
tf2zp Transfer function to Pole-zero representation, see also zp2tf
title Add a title to the current plot
wbw
Returns the bandwidth frequency given the damping ratio and the
rise or settling time.
xlabel/ylabel
Add a label to the horizontal/vertical axis of the current plot, see
also title, text, gtext
zeros Returns a vector or matrix of zeros
zgrid
Generates grid lines of constant damping ratio (zeta) and natural
frequency (Wn), see also sgrid, jgrid, sigrid
zp2ss Pole-zero to state-space representation, see also ss2zp
zp2tf Pole-zero to transfer function representation, see also tf2zp
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
29
Modeling Tutorial
Matlab can be used to represent a physical system or a model. To begin with, let's start
with a review of how to represent a physical system as a set of differential equations.
Train system
In this example, we will consider a toy train consisting of an engine and a car.
Assuming that the train only travels in one direction, we want to apply control to the
train so that it has a smooth start-up and stop, along with a constant-speed ride.
The mass of the engine and the car will be represented by M1 and M2, respectively. The
two are held together by a spring, which has the stiffness coefficient of k. F represents
the force applied by the engine, and the Greek letter, mu (which will also be represented
by the letter u), represents the coefficient of rolling friction.
Photo courtesy: Dr. Howard Blackburn
Free body diagram and Newton's law
The system can be represented by following Free Body Diagrams.
From Newton's law, you know that the sum of forces acting on a mass equals the mass
times its acceleration. In this case, the forces acting on M1 are the spring, the friction
and the force applied by the engine. The forces acting on M2 are the spring and the
friction. In the vertical direction, the gravitational force is canceled by the normal force
applied by the ground, so that there will be no acceleration in the vertical direction. The
equations of motion in the horizontal direction are the followings:
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
30
State-variable and output equations
This set of system equations can now be manipulated into state-variable form. Knowing
state-variables are X1 and X2 and the input is F, state-variable equations will look like
the following:
Let the output of the system be the velocity of the engine. Then the output equation will
become:
1. Transfer function
To find the transfer funciton of the system, first, take Laplace transforms of above state-
variable and output equations.
Using these equations, derive the transfer function Y(s)/F(s) in terms of constants.
When finding the transfer function, zero initial conditions must be assumed. The
transfer function should look like the one shown below.
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
31
2. State-space
Another method to solve the problem is to use the state-space form. Four matrices A, B,
C, and D characterize the system behavior, and will be used to solve the problem. The
state-space form that were manipulated from the state-variable and the output equations
is shown below.
Matlab representation
Now we will show you how to enter the equations derived above into an m-file for
Matlab. Since Matlab can not manipulate symbolic variables, let's assign numerical
values to each of the variables. Let
• M1 = 1 kg
• M2 = 0.5 kg
• k = 1 N/sec
• F= 1 N
• u = 0.002 sec/m
• g = 9.8 m/s^2
Create an new m-file and enter the following commands.
M1=1;
M2=0.5;
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
32
k=1;
F=1;
u=0.002;
g=9.8;
Now you have one of two choices: 1) Use the transfer function, or 2) Use the state-
space form to solve the problem. If you choose to use the transfer function, add the
following commands onto the end of the m-file which you have just created.
num=[M2 M2*u*g 1];
den=[M1*M2 2*M1*M2*u*g M1*k+M1*M2*u*u*g*g+M2*k M1*k*u*g+M2*k*u*g];
If you choose to use the state-space form, add the following commands at the end of the
m-file, instead of num and den matrices shown above.
A=[ 0 1 0 0;
-k/M1 -u*g k/M1 0;
0 0 0 1;
k/M2 0 -k/M2 -u*g];
B=[ 0;
1/M1;
0;
0];
C=[0 1 0 0];
D=[0];
See the Matlab basics tutorial to learn more about entering matrices.
Continue solving the problem
Now, you are ready to obtain the system output (with an addition of few more commands). It should be
noted that many operations can be done using either the transfer function or the state-space model.
Furthermore, it is simple to transfer between the two if the other form of representation is required. If you
need to learn how to convert from one representation to the other, click Conversion.
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
33
Perhitungan dan Pemrograman dengan MATLAB
2.1. Matematika Sederhana
Seperti kalkulator, MATLAB dapat melakukan perhitungan matematika
sederhana.
Contoh : Lakukan perhitungan di bawah ini dengan menggunakan MATLAB
!!!
“Wati berbelanja ke toko buku membeli 10 buku tulis @Rp 1500, 1 buah
penghapus pinsil Rp 1000, dan 2 isi bolpoint @ Rp 800,-“
Maka yang harus dibayarkan oleh Wati adalah :
EDU>>10*1500+1000+2*800
ans =
17600
Dapat pula dihitung dengan menuliskan program :
EDU>> buku=10
buku =
10
EDU>> penghapus=1
penghapus =
1
EDU>> isi = 2;
EDU>> bayar = buku*1500 + penghapus * 1000 + isi * 800
bayar =
17600
MATLAB tidak memperhatikan spasi, untuk sebagian besar, dan perkalian
diprioritaskan terlebih dahulu dari penjumlahan. Juga perlu diketahui,
MATLAB menyebut hasil sebagai ans (singkatan dari answer).
Pada penjumlahan dan perkalian, MATLAB menggunakan operasi aritmatik
dasar berikut ini :
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
34
Operasi Rumus Aritmatik Simbol Penulisan
Penjumlahan a + b + a + b
Pengurangan a – b - a – b
Perkalian a x b * a * b
Pembagian a : b / atau  a / b atau b  a
Pangkat ab
^ a^b
Urutan operasi yang akan dilakukan adalah dengan menggunakan aturan
yang biasa digunakan, yaitu perhitungan dihitung dari kiri ke kanan,
operasi pangkat merupakan urutan pertama, diikuti dengan perkalian dan
pembagian, dan terakhir adalah penjumlah dan pengurangan. Untuk
operasi yang dilakukan dalam tanda kurung, maka operasi itu yang
pertama akan dilakukan dari operasi yang ada di luarnya.
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
35
2.2. Komentar dan Pemberian Tanda Baca
Semua huruf di belakang tanda % dibaca sebagai pernyataan bebas (tidak
mempengaruhi program)
Contoh : EDU>> buku = 10 % jumlah dari buku yang dibeli
buku =
10
Beberapa perintah dapat diletakkan pada satu baris bila dipisah dengan
koma, atau titik koma.
Contoh : EDU>> buku = 10, penghapus = 1; isi = 2
buku =
10
isi =
2
2.3. Bilangan Komplek
Salah satu dari kelebihan MATLAB adalah tidak diperlukannya penanganan
khusus untuk bilangan komplek. Bilangan komplek ditampilkan oleh
MATLAB dengan beberapa cara.
Contoh :
EDU>> c1=1-2i % i menunjukkan bagian imajiner
c1 =
1.0000 – 2.0000i
EDU>> c1=1-2j % j juga bisa digunakan
c1 =
1.0000 – 2.0000i
EDU>> c2=3*(2-sqrt(-1)*3)
c2 =
6.0000 – 9.0000i
EDU>> c3=sqrt(-2)
c3 =
0 + 1.4142 i
dan seterusnya.
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
36
2.4. Fungsi-fungsi Matematika yang umum digunakan
Pernyataan Fungsi
abs(x) nilai absolut atau besar bilangan komplek
acos(x) invers cosinus
acosh(x) invers cosinus hyperbolis
angle(x) sudut 4 kuadrant dari komplek
asin(x) invers sinus
asinh(x) invers sinus hyperbolis
atan(x) invers tangen
atan2(x,y) invers tangen 4 kuadrant
atanh(x) invers tangen hyperbolis
ceil(x) gerak siklus plus tak hingga
conj(x) konjugasi komplek
cos(x) cosinus
cosh(x) cosinus hyperbolis
exp(x) eksponensial (ex
)
fix(x) gerak siklus nol
floor(x) gerak siklus minus tak hingga
gcd(x,y) pembagi terbesar dari bilangan bulat x dan y
imag(x) bagian bilangan imajiner
lcm(x,y) perkalian terkecil dari bilangan bulat x dan y
log(x) logaritma alami
log10(x) logaritma biasa
real(x) bagian bilangan real
rem(x,y)
sisa dari pembagian (rem (x,y) memberikan sisa
dari x/y)
round(x) bilangan bulat terdekat dari siklus lingkar
sign(x) fungsi signum
sin(x) sinus
sinh(x) sinus hyperbolis
sqrt(x) akar persamaan
tan(x) tangen
tanh(x) tangen hyperbolic
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
37
Latihan-latihan Soal dengan MATLAB
Latihan 1 : Perhitungan dengan Matrik
Didalam menulis suatu bentuk matrik, setiap kolom dipisahkan dengan
matrik, dan setiap baris dipisahkan dengan tanda titik koma.
Contoh :
Matrik G =
1 2 3
4 5 6
7 8 9
Maka ditulis :
EDU>> g=[1 2 3;4 5 6;7 8 9]
g =
1 2 3
4 5 6
7 8 9
atau :
EDU>> g=[1 2 3
4 5 6
7 8 9]
g =
1 2 3
4 5 6
7 8 9
EDU>>size(g) % ordo dari matrik a
ans =
22
Fungsi lain matriks yang harus diketahui :
inv(a) ∗ inverse dari matrik a
transpose(a) ∗ transpose dari matrik a
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
38
det(a) ∗ determinan dari matrik a
Soal Latihan :
1. A =
1 2
3 4
a. Tulislah perintah dari MATLAB prompt untuk matrik A
b. Hitunglah transpose dari matrik A
c. Hitunglah determinan dari matrik A
d. Hitunglah invers dari matrik A
e. Buktikan bahwa A-1
=1/det * A?
f. Buktikan bahwa A x A-1
= I
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
39
Latihan 2 : Transfer Function
Untuk menuliskan fungsi dari diagram blok di atas dan kemudian
menuliskannya setelah diberi umpan balik H(s)=1 adalah :
Bila suatu transfer function (fungsi Laplace) akan diubah ke dalam bentuk
perhitungan ruang keadaan (state space equation) untuk diagram blok di
atas di mana
x(t) = ax(t) + bu(t)
y(t) = cx(t) + du(t)
maka ditulis program sebagai berikut :
Buatlah m.file dari kedua program di atas dan lihatlah hasilnya
S + 2
S2
+ 2S + 1
num=[1 2]
den=[1 2 1]
printsys(num,den)
[a,b,c,d]=ss2tf(num,den)
num=[1 2]
den=[1 2 1]
printsys(num,den)
[numcl,dencl]=cloop(num,den)
printsys(numcl,dencl)
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
40
Fungsi – fungsi lain yang harus diketahui :
[num,den]=ss2tf(a,b,c,d)
∗ untuk mengubah dari state space menjadi
transfer function
[nump,denp]=parallel(num1,den1,num2,den2)
∗ menghitung paralel dari dua fungsi
[nums,dens]=series(num1,den1,num2,den2)
∗ menghitung seri dari dua fungsi
[numf,denf]=feedback(num1,den1,numh,denh)
∗ menghitung fungsi alih dengan umpan balik
fungsi H(s)
step(num,den) ∗ melukis tanggapan waktu dari fungsi alih
loop tertutup
figure ∗ untuk membuat window gambar baru
Tugas :
Fungsi 1 :
S + 1
( S + 3 )( S + 5 )
Fungsi 2 :
S + 6
S + 10
a. Hitunglah fungsi alih lingkar tertutup dari fungsi 1 ( H(s) = 1 )
b. Hitunglah fungsi alih dari fungsi 1 dan fungsi 2 yang dihubung paralel.
c. Hitunglah fungsi alih dari fungsi 1 dan fungsi 2 yang dihubung seri.
d. Hitunglah fungsi alih dengan fungsi 2 sebagai umpan balik.
e. Hitung state space equation dari fungsi 1
f. Gambarkan fungsi tanggapan waktu dari fungsi 1
g. Gambarkan fungsi tanggapan waktu dari fungsi 2
Save dengan nama “Latih1.m”
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
41
Latihan 3 : Fungsi Tanggapan Waktu & Tempat Kedudukan Akar
4.3.1. Fungsi Tanggapan Waktu
4.3.1.1. Sistem Orde Satu
Dengan masukan R(s)=1/2, sistem orde satu dapat dinyatakan dengan :
C(s) = R(s)G(s) = a .
s(s+a)
Invers sistem di atas memberikan tanggapan step :
c(t) = cf(t) + cn(t) = 1 – e-at
Dari persamaan di atas terlihat pentingnya parameter a, satu-satunya
parameter yang berpengaruh terhadap tanggapan transien. Jika t = 1/a
e-at
⏐t=1/1 = e-1 = 0.37
atau
x(t) = 1-e-at
⏐t=1/a = 1- 0.37 = 0.63
☺ Konstanta Waktu (Time Constant)
Konstanta waktu adalah waktu yang dibutuhkan sistem untuk mencapai
harga 63% dari harga akhir.
☺ Rise Time, Tr
Rise Time didefinisikan sebgai waktu yang dibutuhkan untuk beranjak dari
titik 10% hingga 90% dari harga akhir. Rumus Tr =
Tr = 2,2
2ζωn
☺ Settling Time, Ts
Settling time didefinisikan sebagai waktu yang dibutuhkan tanggapan
untuk mencapai 98% dari harga akhir. Rumus settling time :
Ts = 4
2ζωn
4.3.1.2. Sistem Orde Dua
Berbeda dengan sistem orde pertama, sistem orde dua mempunyai tingkat
kompleksitas yang lebih besar, lebih banyak parameter yang harus
dianalisa dan diamati untuk dapat menentukan tanggapan sistem.
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
42
Tanggapan pada sistem orde dua ada empat macam :
Tanggapan teredam lebih
Tanggapan kurang teredam
Tanggapan osilasi
Tanggapan teredam kritis
Ada beberapa istilah yang biasa digunakan untuk menyatakan sistem-
sistem berorde dua ini, yang pertama adalah frekuensi alami. Frekuensi
alami ωn adalah frekuensi osilasi sistem tanpa peredaman.
Kedua, adalah damping ratio ζ. Damping ratio ini didefinisikan sebagai
perbandingan antara frekuensi pengurangan eksponensial dengan
frekuensi alaminya. Untuk memperjelas konsep, perhatikan sistem umum
berikut :
G(s) = ωn
2
.
s2
+ 2ζωns + ωn
2
☺ Peak Time, Tp
Peak time adalah waktu yang dibutuhkan untuk mencapai puncak pertama
atau puncak maksimum. Nilai peak time dirumuskan dengan :
2
1 ζω
π
−
=
n
Tp
☺ Percent Overshoot, %OS
Percent overshoot adalah perbandingan selisih harga maksimum dengan
harga akhir sistem (dalam persen). Rumusan untuk mendapatkan nilainya
adalah :
)100/(%ln
100/ln(%
22
OS
OS
+
−
=
π
ζ
☺ Settling Time, Ts
Settling time adalah waktu yang dibutuhkan transien osilasi teredam
untuk berada pada ± 2% harga keadaan tunak. Rumus Ts :
n
sT
ζω
4
=
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
43
☺ Rise Time, Tr
Rise time adalah waktu yang dibutuhkan bentuk gelombang untuk
beranjak dari harga 10% ke 90% harga akhir. Nilai rise time secara analitis
tidak dapat didapat.
n
d
d
tgTr
ζω
ω
ω −
= −11
dimana
2
1 ζωω −= nd
Penulisan perhitungan-perhitungan di atas beberapa diantaranya bila
ditulis dalam MATLAB adalah sebagai berikut :
4.3.2. Tempat Kedudukan Akar
Tempat Kedudukan Akar adalah metoda yang cukup efektif dalam
perancangan dan analisis stabilitas dan tanggapan transien. TKA dapat
digunakan secara kualitatif menerangkan unjuk kerja sebuah sistem
dengan berbagai variasi perubahan parameter. Sebagai contoh, efek
num =
den =
finalvalue = polyval(num,0)/polyval(den,0)
[y,x,t]=step(num,den);
[Y,k]=max(y);
%menghitung time to peak (tp)
timetopeak=t(k)
%menghitung percentovershoot
percentovershoot=100*(Y-finalvalue)/finalvalue
%menghitung rise time (tr)
n=1;
while y(n)<0.1*finalvalue,n=n+1;end
m=1;
while y(m)<0.9*finalvalue,m=m+1;end
risetime=t(m)-t(n)
%menghitung settling time (ts)
l=length(t);
while(y(l)>0.98*finalvalue)&(y(l)<1.02*finalvalue)
l=l-1;
end
settlingtime=t(l)
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
44
variasi penguatan percent overshoot, settling time, dan peak time.
Disamping tanggapan transien, TKA dapat memberikan informasi grafis
tentang stabilitas sebuah sistem. Dapat terlihat secara jelas range
stabilitas, range ketidakstabilan dan kondisi yang menyebabkan sistem
menuju osilasi.
☺ Aturan Perancangan TKA
Beberapa istilah yang berpengaruh dalam perancangan TKA :
1. Jumlah percabangan
2. Simetri
3. Segmen sumbu real
4. Titik awal dan titik akhir
5. Beberapa aturan tambahan.
Untuk melukiskan tempat kedudukan akar dan menentukan k dan poles
dimana :
k = -den(p)/num(p)
dan poles adalah kutub-kutub dari persamaan sistem lingkar terbuka, di
dalam MATLAB adalah :
Tugas :
Sebuah sistem memiliki persamaan sebagai berikut :
num =
den =
wn =
damping =
rlocus(num,den)
sgrid(damping,wn)
axis([-2 2 –6 6])
[k,poles]=rlocfind(num,den)
1
S2
+ 2S + 1
C(s) R(s)
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
45
a. Tentukan Tr, Ts, Td, %OS, ωn
b. Gambarkan Fungsi Tanggapan waktunya
c. Tentukan k dan kutub-kutub dari persamaan di atas
d. Lukiskan Tempat Kedudukan akarnya
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
46
Latihan 4 : Transfer Fungsi Kontinyu – Diskrit, dan Fungsi
Tanggapan Waktu Diskrit dengan metode ZOH dan FOH
4.4.1. Sinyal Waktu Diskrit
Sinyal waktu diskrit timbul bila sistim melibatkan suatu operasi
pencuplikan dari sinyal waktu kontinyu, atau bila sistim melibatkan suatu
proses iteratif yang dibawa oleh komputer digital.
Urutan dari nilai atau angka biasanya ditulis sebagai x(k), dimana k
menunjukkan urutan nilai atau angka muncul pada deret, contoh x(0),
x(1), x(2), …
Bila sinyal waktu kontinyu dicuplik, periode pencuplikan T menjadi
parameter yang penting
4.4.2. Impulse Sampling
Suatu sampling mempunyai periode T, dan duration sampling sangat
singkat.
Sampling ditimbulkan oleh sampler dari fungsi yang kontinyu, menjadi
pulsa train, misal :
t=0, T, 2T, … dengan T, perioda sampling.
Data Hold Circuit, mengkonversikan sample data ke dalam sinyal yang
kontinyu.
Data hold adalah proses pembangkitan sinyal waktu kontinyu h(t) dari
deret waktu diskrit x(kT)
Sinyal h(t) selama interval waktu kT ≤ t ≤ (k+1)T
dapat didekati oleh polinomial dalam τ :
n(kT+τ) = anτn
+ an-1τn-1
+ … + a1τ + a0
untuk 0≤τ≤t, h(kT) = x(kT)
4.4.3. Fungsi Alih Rangkaian Hold
Fungsi alih ZOH : Gh0(s) =
s
sT−
−ε1
dengan ZOH, integrator reset ke nol setelah satu periode sampling.
Fungsi alih FOH : Gh1(s) =
T
Ts
s
sT
11
2
+
⎟⎟
⎠
⎞
⎜⎜
⎝
⎛ − −
ε
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
47
Keluaran h(t) dari FOH adalah garis lurus yang merupakan extrapolasi dari
2 nilai sampling.
Dengan Matlab, semua ketentuan di atas dapat diperoleh dengan cara
yang jauh lebih mudah. Seperti contoh berikut ini :
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
48
Tugas :
Sebuah sistem memiliki persamaan sebagai berikut :
a. Tentukan transformasi Z dengan (Ts = 0.3) loop tertutup dari fungsi di
atas
Ts= 0.5; %periode pencuplikan
num=[1];
den=[1 8 4];
printsys(num,den) %sistem kontinyu loop terbuka
[numc,denc]=cloop(num,den);
printsys(numc,denc) %sistim kontinyu loop tertutup
[numd,dend]=c2dm(numc,denc,Ts); %transformasi kontinyu-diskrit
printsys(numd,dend,'z') %fungsi diskrit
subplot(121), step(numc,denc)
subplot(122), dstep(numd,dend)
figure
[ndf,ddf]=c2dm(numc,denc,Ts,'foh'); %pencuplikan dengan first order hold
printsys(ndf,ddf,'z')
[ndz,ddz]=c2dm(numc,denc,Ts,'zoh'); %pencuplikan dengan zero order hold
printsys(ndz,ddz,'z')
subplot(121), dstep(ndf,ddf)
subplot(122), dstep(ndz,ddz)
1
S2
+ 2S + 1
C(s) R(s)
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
49
b. Buatlah grafik tanggapan waktu kontinyu
c. Buatlah grafik tanggapan waktu diskritnya
d. Buatlah fungsi pencuplikan dengan cara ZOH dan grafiknya
e. Buatlah fungsi pencuplikan dengan cara FOH dan grafiknya.
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
50
Latihan 5 : Kriteria Kestabilan Menurut Jury-Test
Suatu sistem dengan persamaan karakteristik
P(z) = aoZn
+ a1Zn-1
+ … an-1z + an
Sistem stabil bila memenuhi semua kondisi di bawah ini :
1. ⏐an⏐ < ⏐a0⏐
2. P(z)⏐z=1 > 0
3. P(z)⏐z=-1
untukngenp
iluntuknganj
0
0
>
<〈
4. ⏐bn-1⏐ >⏐b0⏐
⏐cn-2⏐ >⏐c0⏐
⏐dn-3⏐ >⏐d0⏐
…
⏐q2⏐ > ⏐q0⏐
dimana :
bk =
10
1
+
−−
k
knn
aa
aa
k = 0,1,2,3,…,n-1
ck =
10
21
+
−−−
k
knn
bb
bb
k = 0,1,2,3,…,n-2
dk =
10
22
+
−−−
k
knn
cc
cc
k = 0,1,2,3,…,n-3
…
qk =
10
23
+
−
k
k
pp
pp
k = 0,1,2
Baris terakhir dari tabel terdiri dari 3 elemen (untuk sistem order-2, 2n-3
= 1 dan tabel Jury hanya berisi satu baris yang terdiri dari tiga elemen.
Elemen-elemen dari baris genap adalah reverse dari peletakan elemen-
elemen baris ganjil.
Contoh dari penulisan program untuk menguji suatu sistim dengan orde 4
adalah :
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
51
%PENGUJIAN KESTABILAN SISTIM DISKRIT ORDE 4
%DENGAN METODE JURY'S TEST
clear
N=5;
disp('Orde sistem = ')
for k=1:5
kt=k-1
a(k)=input ('Masukkan harga a =')
end
pst=polyval(a,1)
pmt=polyval(a,-1)
for k=4:-1:1
matrikb=[a(N) a(N-k);a(1) a(k+1)]
b(k)=det(matrikb)
end
for k=3:-1:1
matrikc=[b(N-1) b(N-1-k);b(1) b(k+1)]
c(k)=det(matrikc)
end
if abs(a(5))<abs(a(1))
s1='Y'
else
s1='N'
end
if pst>0
s2='Y'
else
s2='N'
end
if pmt>0
s3='Y'
else
s3='N'
end
if abs(b(4))>abs(b(1))
s4a='Y'
else
s4a='N'
end
if abs(c(3))>abs(c(1))
s4b='Y'
else
s4b='N'
end
if s1&s2&s3&s4a&s4b=='Y'
sistim='Stabil'
else
sistim='Tidak stabil'
end
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
52
Contoh : Untuk menguji suatu sistim orde 4 yang memiliki persamaan karakteristik =
P(z)=z4
- 1.2z3
+ 0.07z2
+ 0.3z - 0.08
adalah :
EDU» Tan_Jury4
Orde sistem =
kt =
0
Masukkan harga a =1
a =
1
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
53
kt =
1
Masukkan harga a =-1.2
a =
1.0000 -1.2000
kt =
2
Masukkan harga a =.07
a =
1.0000 -1.2000 0.0700
kt =
3
Masukkan harga a =.3
a =
1.0000 -1.2000 0.0700 0.3000
kt =
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
54
4
Masukkan harga a =-0.08
a =
1.0000 -1.2000 0.0700 0.3000 -0.0800
P(z)=z4
- 1.2z3
+ 0.07z2
+ 0.3z - 0.08
pst =
0.0900
P(1) = 0.09
pmt =
1.8900
P(-1) = 1.89
matrikb =
-0.0800 1.0000
1.0000 -0.0800
b =
0 0 0 -0.9936
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
55
matrikb =
-0.0800 -1.2000
1.0000 0.3000
b =
0 0 1.1760 -0.9936
matrikb =
-0.0800 0.0700
1.0000 0.0700
b =
0 -0.0756 1.1760 -0.9936
matrikb =
-0.0800 0.3000
1.0000 -1.2000
b =
-0.2040 -0.0756 1.1760 -0.9936
b0 b1 b2 b3
matrikc =
-0.9936 -0.2040
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
56
-0.2040 -0.9936
c =
0 0 0.9456
matrikc =
-0.9936 -0.0756
-0.2040 1.1760
c =
0 -1.1839 0.9456
matrikc =
-0.9936 1.1760
-0.2040 -0.0756
c =
0.3150 -1.1839 0.9456
c0 c1 c2
s1 =
Y
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
57
s2 =
Y
s3 =
Y
s4a =
Y
s4b =
Y
sistim =
Stabil
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
58
Latihan 6 : Fungsi Tanggapan Frekuensi
Bode Plot
Gambar-gambar Bode melukiskan kestabilan relatif sebuah sistem. Dalam
kenyataannya, margin fasa dan margin gain seringkali didefinisikan dalam
istilah-istilah gambar Bode. Ukuran-ukuran kestabilan relatif ini dapat
ditentukan untuk sebuah sistem tertentu dengan suatu usaha menghitung
yang minimum dengan menggunakan gambar-gambar Bode, khususnya
untuk hal-hal di mana tersedia data tanggapan frekuensi dari percobaan.
Magnituda ⏐P(jω)⏐ dari setiap fungsi P(jω) untuk setiap harga ω
digambarkan pada suatu skala logaritmik dalam satuan-satuan desibel
dimana,
dB ≡ 20 log10 ⏐P(jω)⏐
Karena desibel merupakan suatu satuan logaritmik, magnituda db dari
sebuah fungsi tanggapan frekuensi yang terdiri dari suatu hasilkali suku-
suku adalah sama dengan jumlah magnituda db dari masing-masing suku.
Jadi bila digunakan skala logaritmik, gambar magnituda dari sebuah
fungsi tanggapan frekuensi yang dapat dinyatakan sebagai hasil kali lebih
dari satu suku dapat diperoleh dengan menjumlahkan masing-masing
gambar magnituda db untuk setiap suku hasilkali.
Gambar magnituda db versus logω disebut gambar magnituda Bode, dan
gambar sudut fasa versus logω adalah gambar sudut fasa Bode. Dalam
kepustakaan kadang-kadang gambar magnituda Bode disebut gambar Log-
modulus.
Bentuk Bode untuk fungsi :
))...()((
))...()((
)(
21
21
n
m
n
pspspss
zszszsK
sG
+++
+++
=
dimana m adalah bilangan bulat tak negatif, diperoleh dengan
menguraikan semua z dan p dan menyusunnya kembali dalam bentuk :
ωjs
pspspss
zszszsK
sG
n
m
n
→
+++
+++
=
)(...)()(
(...)()(
)(
21
)21
Pengubahan tanggapan magnitudo ke dalam dB menghasilkan
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
59
20 log ⏐G(jω)⏐= 20 log K + 20 log ⏐(s+z1)⏐ + 20 log ⏐(s+z2)⏐ +…
-20 log ⏐(sm
)⏐ + 20 log ⏐(s+p1)⏐- … ⏐s → jω
Sementara fasa dari fungsi adalah 1/sm
dimana s= jω adalah :
[ ])(arg ωjP
Contoh program dengan Matlab untuk membuat Bode Plot dari suatu
sistim dengan persamaan karakteristik :
)10)(15.0(
)22.0(*10
)( 2
2
+++
++
=
sss
ss
sF
adalah :
Bode representation
The Bode plots take each one of the points on the above plot and breaks it down into
magnitude and phase. The magnitude is then plotted as gain in decibels and the
phase is plotted in degrees. The frequency (on the independent axis) is plotted on a
logarithmic scale. Let's take a look at the Bode plots for this function and see if our
answers match.
bode(num,den)
% Sistem yang diberikan
num=10*[1 0.2 2];
den=conv([1 0.5 1],[1 10]);%(s^2+0.5s+1)(s+10)
disp('Persamaan sistem =')
printsys(num,den,'s')
% Diskrit dari Sistem dengan Zero Order Hold
Ts=0.3
[numd,dend]=c2dm(num,den,Ts,'zoh');
%Contoh membuat Bode dari Sistem
bode(num,den)
dbode(numd,dend,Ts)
Title('Contoh Bode Plot')
xlabel('Frekuensi (rad/sec)')
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
60
If you look at the plots at a frequency of 3rad/s you will see the magnitude is a little
over 2.5 dB and the phase is around 140 degrees. This agrees with our previous
results.
Tugas :
Sebuah sistem memiliki persamaan karakteristik sebagai berikut :
)5)(12(
)13.0(*15
)( 2
2
+++
++
=
sss
ss
sF
Buatlah Bode Plot dari fungsi tersebut
Nyquist
Plotting Frequency Response
In order to illustrate the plotting of G(jw), we will generate our own plot of
G(j*w)and compare it with the Bode plots and the Nyquist diagram. If we run the
following m-file, we will see the points that comprise G(jw), in particular the point
corresponding to G(j*3).
%define the transfer function
num = conv([1,4],[1 6]);
den = conv([1,-3],[1 -5]);
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
61
%create a frequency vector
clf
w = logspace(-1,2,100);
hold on
%plot a '+' for each point corresponding to G(jw)
for i = 1:100
plot(polyval(num,j*w(1,i))/polyval(den, j*w (1,i)), '+')
end
%plot a green 'X' for frequency of 3rad/s
plot(polyval(num,j*3)/polyval(den, j*3), 'xg')
%plot vector from origin to this point
n= polyval(num,j*3)/polyval(den, j*3);
x = [0,real(n)];
y = [0,imag(n)];
plot(x,y, '-g')
%find magnitude and phase
Mag = abs(n);
Phase = 180 +360*atan(imag(n)/real(n))/(2*pi);
%find gain
Gain = 20*log10(Mag);
grid
Mag, Phase, Gain
The image should look similar to this:
Please note that each yellow cross represents the transfer function evaluated at a
specific frequency and that only positive frequencies are used. Also note the point
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
62
and vector associated with a frequency of 3 rad/s (green). In the Matlab command
window, you should see the Magnitude, Phase, and Gain (in dB) associated with this
vector:
Note: a decibel is defined as 20*log10 ( |G(j*w| )
Mag =
1.3558
Phase =
139.3987
Gain =
2.6440
Now that we know where Bode plots come form, let's see where Nyquist plots come from. The
Nyquist diagram is basically a plot of G(j*w). However, both positive and negative frequencies
of the contour we showed previously are taken into account. Let's plot the Nyquist diagram on
top of our G(j*w) plot (this time, we will include the negative frequencies as well).
%define the transfer function
num = conv([1,4],[1 6]);
den = conv([1,-3],[1 -5]);
%create a frequency vector similar to the one described above
w = logspace(-1,2,100);
negw = -1*w;
clf
hold on
%plot a '+' for each point corresponding to G(jw)
for i = 1:100
plot(polyval(num,j*w(1,i))/polyval(den, j*w (1,i)), '+')
plot(polyval(num,j*negw(1,i))/polyval(den, j*negw (1,i)), '+')
end
%draw Nyquist diagram on top to compare
nyquist(num,den)
hold off
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
63
A perfect match! Also note that the negative frequencies produce a mirror image
across the real axis of the positive frequency response.
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
64
Gain and Phase Margin
Let's say that we have the following system:
where K is a variable (constant) gain and G(s) is the plant under consideration. The
gain margin is defined as the change in open loop gain required to make the system
unstable. Systems with greater gain margins can withstand greater changes in system
parameters before becoming unstable in closed loop.
Keep in mind that unity gain in magnitude is equal to a gain of zero in dB.
The phase margin is defined as the change in open loop phase shift required to make
a closed loop system unstable.
The phase margin also measures the system's tolerance to time delay. If there is a
time delay greater than 180/Wpc in the loop (where Wpc is the frequency where the
phase shift is 180 deg), the system will become unstable in closed loop. The time
delay can be thought of as an extra block in the forward path of the block diagram
that adds phase to the system but has no effect the gain. That is, a time delay can
be represented as a block with magnitude of 1 and phase w*time_delay (in
radians/second).
For now, we won't worry about where all this comes from and will concentrate on
identifying the gain and phase margins on a Bode plot:
The phase margin is the difference in phase between the phase curve and -180 deg at
the point corresponding to the frequency that gives us a gain of 0dB (the gain cross
over frequency, Wgc). Likewise, the gain margin is the difference between the
magnitude curve and 0dB at the point corresponding to the frequency that gives us a
phase of -180 deg (the phase cross over frequency, Wpc).
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
65
One nice thing about the phase margin is that you don't need to replot the Bode in
order to find the new phase margin when changing the gains. If you recall, adding
gain only shifts the magnitude plot up. This is the equivalent of changing the y-axis
on the magnitude plot. Finding the phase margin is simply the matter of finding the
new cross-over frequency and reading off the phase margin. For example, suppose
you entered the command bode(50,[1 9 30 40]). You will get the following bode plot:
You should see that the phase margin is about 100 degrees. Now suppose you added a
gain of 100, by entering the command bode(100*50,[1 9 30 40]). You should get the
following plot (note I changed the axis so the scale would be the same as the plot
above, your bode plot may not be exactly the same shape, depending on the scale
used):
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
66
As you can see the phase plot is exactly the same as before, and the magnitude plot
is shifted up by 40dB (gain of 100). The phase margin is now about -60 degrees. This
same result could be achieved if the y-axis of the magnitude plot was shifted down
40dB. Try this, look at the first Bode plot, find where the curve crosses the -40dB
line, and read off the phase margin. It should be about -60 degrees, the same as the
second Bode plot.
We can find the gain and phase margins for a system directly, by using Matlab. Just
enter the margin command. This command returns the gain and phase margins, the
gain and phase cross over frequencies, and a graphical representation of these on the
Bode plot. Let's check it out:
margin(50,[1 9 30 40])
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
67
Latihan : 7 Designing Lead and Lag Compensators
Lead and lag compensators are used quite extensively in control. A lead compensator
can increase the stability or speed of response of a system; a lag compensator can
reduce (but not eliminate) the steady state error. Depending on the effect desired,
one or more lead and lag compensators may be used in various combinations.
Lead, lag, and lead/lag compensators are usually designed for a system in transfer
function form. The conversions page explains how to convert a state-space model
into transfer function form.
Lead or phase-lead compensator using root locus
A first-order lead compensator can be designed using the root locus. A lead
compensator in root locus form is given by
where the magnitude of zo is less than the magnitude of po. A phase-lead
compensator tends to shift the root locus toward the left half plane. This results in
an improvement in the system's stability and an increase in the response speed.
How is this accomplished? If you recall finding the asymptotes of the root locus that
lead to the zeros at infinity, the equation to determine the intersection of the
asymptotes along the real axis is:
When a lead compensator is added to a system, the value of this intersection will be
a larger negative number than it was before. The net number of zeros and poles will
be the same (one zero and one pole are added), but the added pole is a larger
negative number than the added zero. Thus, the result of a lead compensator is that
the asymptotes' intersection is moved further into the left half plane, and the entire
root locus will be shifted to the left. This can increase the region of stability as well
as the response speed.
In Matlab a phase lead compensator in root locus form is implemented by using the
transfer function in the form
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
68
numlead=kc*[1 z];
denlead=[1 p];
and using the conv() function to implement it with the numerator and denominator
of the plant
newnum=conv(num,numlead);
newden=conv(den,denlead);
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
69
Lead or phase-lead compensator using frequency
response
A first-order phase-lead compensator can be designed using the frequency response.
A lead compensator in frequency response form is given by
Note that this is equivalent to the root locus form
with p = 1/T, z = 1/aT, and Kc = a. In frequency response design, the phase-lead
compensator adds positive phase to the system over the frequency range 1/aT to
1/T. A bode plot of a phase-lead compensator looks like the following
The two corner frequencies are at 1/aT and 1/T; note the positive phase that is
added to the system between these two frequencies. Depending on the value of a,
the maximum added phase can be up to 90 degrees; if you need more than 90
degrees of phase, two lead compensators can be used. The maximum amount of
phase is added at the center frequency, which is located at
The equation which determines the maximum phase is
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
70
Additional positive phase increases the phase margin and thus increases the stability
of the system. This type of compensator is designed by determining a from the
amount of phase needed to satisfy the phase margin requirements, and determining
T to place the added phase at the new gain-crossover frequency.
Another effect of the lead compensator can be seen in the magnitude plot.
The lead compensator increases the gain of the system at high frequencies
(the amount of this gain is equal to a). This can increase the crossover frequency,
which will help to decrease the rise time and settling time of the system.
In Matlab, a phase lead compensator in frequency response form is implemented by
using the transfer function in the form
numlead=[aT 1];
denlead=[T 1];
and using the conv() function to multiply it by the numerator and denominator of the
plant
newnum=conv(num,numlead);
newden=conv(den,denlead);
Lag or Phase-Lag Compensator using Root Locus
A first-order lag compensator can be designed using the root locus. A lag
compensator in root locus form is given by
where the magnitude of zo is greater than the magnitude of po. A phase-lag
compensator tends to shift the root locus to the right, which is undesirable. For this
reason, the pole and zero of a lag compensator must be placed close together
(usually near the origin) so they do not appreciably change the transient response or
stability characteristics of the system.
How does the lag controller shift the root locus to the right? If you recall finding the
asymptotes of the root locus that lead to the zeros at infinity, the equation to
determine the intersection of the asymptotes along the real axis is:
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
71
When a lag compensator is added to a system, the value of this intersection will be a
smaller negative number than it was before. The net number of zeros and poles will
be the same (one zero and one pole are added), but the added pole is a smaller
negative number than the added zero. Thus, the result of a lag compensator is that
the asymptotes' intersection is moved closer to the right half plane, and the entire
root locus will be shifted to the right.
It was previously stated that that lag controller should only minimally change the
transient response because of its negative effect. If the phase-lag compensator is not
supposed to change the transient response noticeably, what is it good for? The
answer is that a phase-lag compensator can improve the system's steady-state
response. It works in the following manner. At high frequencies, the lag controller
will have unity gain. At low frequencies, the gain will be z0/p0 which is greater than
1. This factor z0/p0 will multiply the position, velocity, or acceleration constant (Kp,
Kv, or Ka), and the steady-state error will thus decrease by the factor z0/p0.
In Matlab, a phase lead compensator in root locus form is implemented by using the
transfer function in the form
numlag=[1 z];
denlag=[1 p];
and using the conv() function to implement it with the numerator and denominator
of the plant
newnum=conv(num,numlag);
newden=conv(den,denlag);
Lag or Phase-Lag Compensator using Frequency
Response
A first-order phase-lag compensator can be designed using the frequency response. A
lag compensator in frequency response form is given by
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
72
The phase-lag compensator looks similar to a phase-lead compensator, except that a
is now less than 1. The main difference is that the lag compensator adds negative
phase to the system over the specified frequency range, while a lead compensator
adds positive phase over the specified frequency. A bode plot of a phase-lag
compensator looks like the following
The two corner frequencies are at 1/T and 1/aT. The main effect of the lag
compensator is shown in the magnitude plot. The lag compensator adds gain at low
frequencies; the magnitude of this gain is equal to a. The effect of this gain is to
cause the steady-state error of the closed-loop system to be decreased by a factor of
a. Because the gain of the lag compensator is unity at middle and high frequencies,
the transient response and stability are not impacted too much.
The side effect of the lag compensator is the negative phase that is added to the
system between the two corner frequencies. Depending on the value a, up to -90
degrees of phase can be added. Care must be taken that the phase margin of the
system with lag compensation is still satisfactory.
In Matlab, a phase-lag compensator in frequency response form is implemented by
using the transfer function in the form
numlead=[a*T 1];
denlead=a*[T 1];
Materi Pendukung Kuliah : Sistim Pengaturan
(Perhitungan, Pemrograman dan Visualisasi dengan MATLAB)
73
and using the conv() function to implement it with the numerator and denominator
of the plant
newnum=conv(num,numlead);
newden=conv(den,denlead);
Lead-lag Compensator using either Root Locus or Frequency
Response
A lead-lag compensator combines the effects of a lead compensator with those of a
lag compensator. The result is a system with improved transient response, stability
and steady-state error. To implement a lead-lag compensator, first design the lead
compensator to achieve the desired transient response and stability, and then add on
a lag compensator to improve the steady-state response.

More Related Content

What's hot

Artikel Counter sinkron dan asinkron
Artikel Counter sinkron dan asinkronArtikel Counter sinkron dan asinkron
Artikel Counter sinkron dan asinkronIGustingurahKanha
 
Fungsi alih sistem kontrol
Fungsi alih sistem kontrolFungsi alih sistem kontrol
Fungsi alih sistem kontrolarie eric
 
Buku e analisis-rangkaian-listrik-jilid-2 (1)
Buku e analisis-rangkaian-listrik-jilid-2 (1)Buku e analisis-rangkaian-listrik-jilid-2 (1)
Buku e analisis-rangkaian-listrik-jilid-2 (1)kiplaywibley
 
Materi Amplitude Modulation (AM)
Materi Amplitude Modulation (AM) Materi Amplitude Modulation (AM)
Materi Amplitude Modulation (AM) Ferdi Dirgantara
 
Jenis dan proses interupsi
Jenis dan proses interupsiJenis dan proses interupsi
Jenis dan proses interupsilaurensius08
 
Modul teknik-digital
Modul teknik-digitalModul teknik-digital
Modul teknik-digitalecko gmc
 
Menjelaskan prinsip register
Menjelaskan prinsip registerMenjelaskan prinsip register
Menjelaskan prinsip registerEko Supriyadi
 
Karakteristik Transistor
Karakteristik TransistorKarakteristik Transistor
Karakteristik TransistorRyan Aryoko
 
Sistem linier dan non linier
Sistem linier dan non linierSistem linier dan non linier
Sistem linier dan non liniermuhamadaulia3
 
Bab 5 penyederhanaan fungsi boolean
Bab 5 penyederhanaan fungsi booleanBab 5 penyederhanaan fungsi boolean
Bab 5 penyederhanaan fungsi booleanCliquerz Javaneze
 
Pertemuan 6 & 7 ars. gerbang logika
Pertemuan 6 & 7 ars. gerbang logikaPertemuan 6 & 7 ars. gerbang logika
Pertemuan 6 & 7 ars. gerbang logikaBuhori Muslim
 
Rangkaian Listrik Resonansi
Rangkaian Listrik ResonansiRangkaian Listrik Resonansi
Rangkaian Listrik ResonansiFauzi Nugroho
 
Gerbang logika
Gerbang logikaGerbang logika
Gerbang logikaputusumaye
 
Prinsip kerja PID
Prinsip kerja PIDPrinsip kerja PID
Prinsip kerja PIDSupar Ramah
 

What's hot (20)

Artikel Counter sinkron dan asinkron
Artikel Counter sinkron dan asinkronArtikel Counter sinkron dan asinkron
Artikel Counter sinkron dan asinkron
 
Difu difd
Difu difdDifu difd
Difu difd
 
Ampifier & Op-Amp
Ampifier & Op-AmpAmpifier & Op-Amp
Ampifier & Op-Amp
 
Fungsi alih sistem kontrol
Fungsi alih sistem kontrolFungsi alih sistem kontrol
Fungsi alih sistem kontrol
 
Buku e analisis-rangkaian-listrik-jilid-2 (1)
Buku e analisis-rangkaian-listrik-jilid-2 (1)Buku e analisis-rangkaian-listrik-jilid-2 (1)
Buku e analisis-rangkaian-listrik-jilid-2 (1)
 
1 sinyal
1  sinyal1  sinyal
1 sinyal
 
Materi Amplitude Modulation (AM)
Materi Amplitude Modulation (AM) Materi Amplitude Modulation (AM)
Materi Amplitude Modulation (AM)
 
Jenis dan proses interupsi
Jenis dan proses interupsiJenis dan proses interupsi
Jenis dan proses interupsi
 
Sistem kontrol proses
Sistem kontrol proses Sistem kontrol proses
Sistem kontrol proses
 
SISTEM KONTROL
SISTEM KONTROLSISTEM KONTROL
SISTEM KONTROL
 
Modul teknik-digital
Modul teknik-digitalModul teknik-digital
Modul teknik-digital
 
Menjelaskan prinsip register
Menjelaskan prinsip registerMenjelaskan prinsip register
Menjelaskan prinsip register
 
Karakteristik Transistor
Karakteristik TransistorKarakteristik Transistor
Karakteristik Transistor
 
Laporan praktikum karakteristik dioda
Laporan praktikum karakteristik diodaLaporan praktikum karakteristik dioda
Laporan praktikum karakteristik dioda
 
Sistem linier dan non linier
Sistem linier dan non linierSistem linier dan non linier
Sistem linier dan non linier
 
Bab 5 penyederhanaan fungsi boolean
Bab 5 penyederhanaan fungsi booleanBab 5 penyederhanaan fungsi boolean
Bab 5 penyederhanaan fungsi boolean
 
Pertemuan 6 & 7 ars. gerbang logika
Pertemuan 6 & 7 ars. gerbang logikaPertemuan 6 & 7 ars. gerbang logika
Pertemuan 6 & 7 ars. gerbang logika
 
Rangkaian Listrik Resonansi
Rangkaian Listrik ResonansiRangkaian Listrik Resonansi
Rangkaian Listrik Resonansi
 
Gerbang logika
Gerbang logikaGerbang logika
Gerbang logika
 
Prinsip kerja PID
Prinsip kerja PIDPrinsip kerja PID
Prinsip kerja PID
 

Viewers also liked

Dasar control system dengan matlab
Dasar control system dengan matlabDasar control system dengan matlab
Dasar control system dengan matlabadi_yus
 
Contoh program matlab
Contoh program matlabContoh program matlab
Contoh program matlabZahra Doangs
 
Membuat Aplikasi Penghitung Luas Persegi Panjang Pada MATLAB
Membuat Aplikasi Penghitung Luas Persegi Panjang Pada MATLABMembuat Aplikasi Penghitung Luas Persegi Panjang Pada MATLAB
Membuat Aplikasi Penghitung Luas Persegi Panjang Pada MATLABYunan Tanpa-i
 
Pengantar Teknik Industri
Pengantar Teknik IndustriPengantar Teknik Industri
Pengantar Teknik IndustriHIMTI
 
Membuat program kalkulator sederhana dengan matlab
Membuat program kalkulator sederhana dengan matlabMembuat program kalkulator sederhana dengan matlab
Membuat program kalkulator sederhana dengan matlabNur Halimah
 
Matlab Untuk Pengolahan Citra
Matlab Untuk Pengolahan CitraMatlab Untuk Pengolahan Citra
Matlab Untuk Pengolahan Citraarifgator
 
Praktik dengan matlab
Praktik dengan matlabPraktik dengan matlab
Praktik dengan matlabSyafrizal
 
Pengolahan Citra Digital Dengan Menggunakan MATLAB
Pengolahan Citra Digital Dengan Menggunakan MATLABPengolahan Citra Digital Dengan Menggunakan MATLAB
Pengolahan Citra Digital Dengan Menggunakan MATLABSimesterious TheMaster
 

Viewers also liked (8)

Dasar control system dengan matlab
Dasar control system dengan matlabDasar control system dengan matlab
Dasar control system dengan matlab
 
Contoh program matlab
Contoh program matlabContoh program matlab
Contoh program matlab
 
Membuat Aplikasi Penghitung Luas Persegi Panjang Pada MATLAB
Membuat Aplikasi Penghitung Luas Persegi Panjang Pada MATLABMembuat Aplikasi Penghitung Luas Persegi Panjang Pada MATLAB
Membuat Aplikasi Penghitung Luas Persegi Panjang Pada MATLAB
 
Pengantar Teknik Industri
Pengantar Teknik IndustriPengantar Teknik Industri
Pengantar Teknik Industri
 
Membuat program kalkulator sederhana dengan matlab
Membuat program kalkulator sederhana dengan matlabMembuat program kalkulator sederhana dengan matlab
Membuat program kalkulator sederhana dengan matlab
 
Matlab Untuk Pengolahan Citra
Matlab Untuk Pengolahan CitraMatlab Untuk Pengolahan Citra
Matlab Untuk Pengolahan Citra
 
Praktik dengan matlab
Praktik dengan matlabPraktik dengan matlab
Praktik dengan matlab
 
Pengolahan Citra Digital Dengan Menggunakan MATLAB
Pengolahan Citra Digital Dengan Menggunakan MATLABPengolahan Citra Digital Dengan Menggunakan MATLAB
Pengolahan Citra Digital Dengan Menggunakan MATLAB
 

Similar to Dasar control system dengan matlab

Similar to Dasar control system dengan matlab (20)

Matlab
MatlabMatlab
Matlab
 
Matlab Tutorial Chapter 1
Matlab Tutorial Chapter 1Matlab Tutorial Chapter 1
Matlab Tutorial Chapter 1
 
Matlab pemula
Matlab pemulaMatlab pemula
Matlab pemula
 
Modul 1 pengenalan matlab
Modul 1 pengenalan matlabModul 1 pengenalan matlab
Modul 1 pengenalan matlab
 
Matlab Tutorial Chapter 2
Matlab Tutorial Chapter 2Matlab Tutorial Chapter 2
Matlab Tutorial Chapter 2
 
Praktikum pemrograman modul i
Praktikum pemrograman modul iPraktikum pemrograman modul i
Praktikum pemrograman modul i
 
Cepat mahir dengan matlab
Cepat mahir dengan matlabCepat mahir dengan matlab
Cepat mahir dengan matlab
 
Operasi dasar matlab job 1
Operasi dasar matlab job 1Operasi dasar matlab job 1
Operasi dasar matlab job 1
 
Praktik matlab
Praktik matlabPraktik matlab
Praktik matlab
 
Matlab
MatlabMatlab
Matlab
 
Dasar matlab
Dasar matlabDasar matlab
Dasar matlab
 
Dasar matlab
Dasar matlabDasar matlab
Dasar matlab
 
Matlab
MatlabMatlab
Matlab
 
Matlab
MatlabMatlab
Matlab
 
Matlab
MatlabMatlab
Matlab
 
Tutorialmatlab bahasa indonesia
Tutorialmatlab bahasa indonesiaTutorialmatlab bahasa indonesia
Tutorialmatlab bahasa indonesia
 
Tutorial matlab .pdf
Tutorial matlab .pdfTutorial matlab .pdf
Tutorial matlab .pdf
 
Tutorial matlab libre
Tutorial matlab libreTutorial matlab libre
Tutorial matlab libre
 
Matlab Tutorial
Matlab TutorialMatlab Tutorial
Matlab Tutorial
 
Tutorial matlab
Tutorial matlabTutorial matlab
Tutorial matlab
 

Dasar control system dengan matlab

  • 1. Bab 1 Pendahuluan MATLAB berasal dari kata Matrix Laboratory. Versi pertamanya ditulis di University of New Mexico dan Stanford University pada akhir tahun 70-an, dimaksudkan untuk memecahkan permasalahan di teori matriks, aljabar linier, dan analisa numerik. Sebelumnya telah dikenal program-program LINPACK DAN EISPACK, yang dikemas dalam FORTRAN untuk perhitungan matriks. MATLAB yang saat ini digunakan kemampuannya melampaui Matrix Laboratory yang sebenarnya. MATLAB adalah bahasa pemrograman tingkat tinggi untuk perhitungan teknik. Isinya mencakup perhitungan, visualisasi, dan pemrograman dalam lingkungan yang mudah digunakan dimana masalah dan solusinya ditampilkan dalam notasi matematika yang sudah dikenal. Fungsi-fungsinya meliputi : Matematika dan komputasi Pengembangan Algoritma Modelling, simulasi, dan pembuatan proto-type Analisa data, eksplorasi, dan visualisasi Ilmu pengetahuan dan grafik teknik, Pengembangan aplikasi, termasuk pembuatan antarmuka pengguna secara grafis. MATLAB terus berkembang dari tahun ke tahun dengan berbagai masukan dari para pengguna MATLAB. Versi Matlab meliputi hal-hal yang terkait di setiap bagian MATLAB dari deret matematika dan konstruksi bahasa pemrograman, sampai stuktur data dan metoda-metoda orientasi objek, untuk visualisasi dan perlengkapan pembuatan GUI MATLAB adalah suatu lingkungan dan bahasa pemrograman , dan satu dari kelebihannya ada kenyataan bahwa bahasa MATLAB memungkinan kita untuk membuat peralatan yang bisa dipakai ulang. Fungsi-fungsi dan program-program khusus dapat ditulis secara mudah di dalam kode MATLAB. Sebagaimana fungsi-fungsi MATLAB terus ditulis untuk memecahkan masalah-masalah tertentu, tentu diperlukan meng-kelompokan fungsi-fungsi yang berhubungan menjadi satu direktori. Hal ini adalah konsep dasar dari Toolbox: kumpulan khusus dari M-file untuk bekerja pada masalah-masalah tertentu.
  • 2. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 2 Penggunaan M-files dalam Matlab Ada perbedaan penggunaan Matlab di dalam platform yang berbeda : Macintosh Terdapat sebuah built-in editor untuk m-files; pilih "New M-file" dari menu File. Editor lainnya juga dapat digunakan (tapi pastikan ahwa file telah disave dalam format text, dan dapat diload bila akan mulai menggunakan Matlab). Windows Menggunakan Matlab dalam Windows serupa dengan cara menggunakannya di dalam Macintosh. Akan tetapi, perlu diketahui bahwa m-file akan disimpan di dalam clipboard. Karenanya, perlu dipastikan bahwa m-file telah disimpan sebagai namafile.m . Unix Di dalam unix, editor dijalankan secara terpisah dari Matlab. Cara terbaik adalah dengan membuat sebuah direktori untuk semua m-files, kemudian cd ke direktori yang dimaksud sebelum menjalankan Matlab maupun editor. Untuk mulai menggunakan Matlab dari window Xterm hanya perlu dengan mengetikkan : matlab. Perintah juga dapat diketikkan langsung ke dalam matlab, atau taruh semua dari perintah yang diperlukan untuk bersama-sama di dalam sebuah an m-file, dan hanya jalankan file. Bila semua m-files diletakkan dalam directory yang sama dengan direktori tempat matlab dijalankan, maka matlab akan selalu menjalankannya. Menu help dalam Matlab Matlab memberikan menu help dengan cukup mengetikkan : help commandname
  • 3. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 3 Pengertian m-file Sebuah m-file atau file script, adalah file teks yang sederhana yang berisi perintah Matlab. Bila file ini dijalankan, Matlab membaca command ini dan mengeksekusinya sebagaimana bila setiap command diketik langsung pada prompt Matlab. Semua m-file memiliki ekstensi “. m”. Bila sebuah m-file baru dibuat dengan nama yang sama dengan yang telah ada di m-file yang sudah ada, Matlab akan memilih m-file yang lebih dahulu berada di urutan path. Untuk itu, buatlah m-file dengan nama yang belum ada di default Matlab, bisa dicoba dengan diberi nama dalam bahasa Indonesia. Untuk mengetahui file mana yang sudah ada, ketik help filename pada prompt Matlab Alasan Menggunakan m-file Untuk permasalahan yang sederhana, mengetikkan perintah langsung pada prompt Matlab adalah hal yang mudah, akan tetapi, jumlah baris dari command makin lama makin banyak, dan bila sedang melakukan suatu percobaan, maka bila harus mengetikkannya berkali-kali adalah hal yang sia-sia. Dalam hal ini, m-file dapat membantu, bahkan penting untuk menghindar dari masalah ini. Cara Menjalankan m-file Setela m-file disimpan dengan nama *.m pada folder Matlab, atau direktori, file ini dapat dieksekusi hanya dengan mengetikkan nama file pada prompt Matlab Cara Membuat m-file Untuk membuat M-file pada PC, pilih New dari File menu dan pilih M-file. Prosedur ini akan menampilkan text editor window dimana perintah-perintah MATLAB dapat diberikan.. Tampilan berikut menunjukkan perintah yang dikirimkan melalui file skrip. % Contoh.m file skrip untuk masalah acid water bath initial_con=90 min_con=50 lost=0.01; n=floor(log2(initial_con/min_con)/log2(1+lost))
  • 4. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 4 File ini disimpan sebagai M-file contoh.m pada disket dengan memilih Save dari menu File, kemudian MATLAB akan menjalankan perintah dari contoh.m pada saat contoh diketikkan pada prompt MATLAB: Dikarenakan perlengkapan dari file skrip, MATLAB melengkapi beberapa fungsi yang berguna bila digunakan di dalam M-file, yaitu : Perintah Arti disp(ans) menampilkan hasil tanpa mengindentifikasi nama variabel echo mengendalikan command window mengulang perintah-perintah pada file skrip input prompt buatan untuk masukan keyboard memberikan kendali pada keyboard secara temporary (ketik return untuk keluar) pause berhenti sampai sembarang tombol keyboard ditekan pause(n) berhenti untuk n detik waitforbuttonp ress berhenti sampai pemakai menekan tombol mouse atau key keyboard Contoh : % Contoh.m file skrip untuk masalah acid water bath initial_con=90 min_con=50 lost=input(‘Masukkan persentasi kehilangan dengan setiap dip >’)/100 n=floor(log2(initial_con/min_con)/log2(1+lost)) EDU>>contoh initial_con= 90 min_con= 50 n = 59
  • 5. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 5 Hasil file skrip : Contoh : Hasil : echo on % Contoh.m file skrip untuk masalah acid water bath initial_con=90 min_con=50 lost=input(‘Masukkan persentasi kehilangan dengan setiap dip >’)/100 n=floor(log2(initial_con/min_con)/log2(1+lost)) echo off EDU>> contoh % Contoh.m file skrip untuk masalah acid water bath initial_con=90 initial_con = 90 min_con=50 min_con = 50 lost=input(‘Masukkan persentasi kehilangan dengan setiap dip >’)/100 Masukkan persentasi kehilangan dengan setiap dip > 20 lost = 0.2 n=floor(log2(initial_con/min_con)/log2(1+lost)) n = 3 echo off Masukkan persentasi kehilangan dengan setiap dip > 5 lost = 0.05 n = 12
  • 6. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 6 Tutorial Dasar Matlab Matlab adalah program interaktif untuk komputasi numeric dan visualisasi data yang umum digunakan oleh ilmuwan kendali untuk analisa dan perancangan. Ada berbagai toolbox yang berbeda yang dapat digunakan untuk berbagai area aplikasi yang berbeda. Untuk diktat ini, hanya penggunaan pada bidang sistem kendali yang akan dibahas. Vektor Sebagai permulaan, matlab akan digunakan untuk suatu permasalahan yang sederhana seperti vector. Setiap elemen dari vector akan disusun dengan dipisahkan oleh space di dalam tanda kurung. Sebagai contoh, dapat diketik seperti berikut ini pada command window dari program matlab : Matlab akan kembali menuliskan : Untuk menyusun deret bilangan dari 0 sampai dengan 20 dengan jarak 2 maka diketikkan : Untuk memanipulasi vector dengan menambahkan dua kepada setiap elemen dari vector a, maka persamaannya adalah : a = 1 2 3 4 5 6 9 8 7 a = [1 2 3 4 5 6 9 8 7] t = 0:2:20 t = 0 2 4 6 8 10 12 14 16 18 20 b = a + 2 b = 3 4 5 6 7 8 11 10 9
  • 7. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 7 Bila kedua vector, yaitu a dan b akan ditambahkan, dan seterusnya c = a + b c = 4 6 8 10 12 14 20 18 16
  • 8. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 8 Fungsi-Fungsi Matlab Matlab telah menyediakan beberapa fungsi standar. Setiap fungsi adalah satu blok kode yang mengerjakan tugas tertentu. Pada matlab telah meliputi fungsi-fungsi standar yaitu : sin, cos, log, exp, sqrt, dan sebagainya. Biasanya, konstanta seperti pi, and i or j untuk akar dari -1, juga telah termasuk dalam Matlab. Untuk mengetahui fungsi dari fungsi-fungsi yang ada, ketikkan : help [function name] pada Matlab command window. Saat menuliskan perintah seperti roots, plot, atau step ke dalam Matlab, sebenarnya yang sedang dilakukan adalah menjalankan sebuah m-file dengan masukan dan keluaran yang telah ditulis untuk memenuhi tugas tertentu. Jenis m-file ini serupa dengan subrutin dalam bahasa pemrograman yang memiliki masukkan (parameter yang telah dimasukkan ke dalam m-file), keluaran (nilai yang diperoleh dari m-file), dan satu badan perintah-perintah yang berisi variabel local. Matlab menyebu m-file ini sebagai function (fungsi). Untuk itu, sebuah perintah function dapat ditulis baru, sesuai tujuan, artinya, sebuah toolbox baru dapat disusun. Fungsi baru adalah sebuah m-file dan memiliki ekstensi file “. m”. File ini disimpan pada direktori yang sama dengan software Matlab, atau di dalam direktori yang berisi path yang diacu oleh Matlab. Baris pertama sebuah function haruslah berikut ini : function [output1,output2] = filename(input1,input2,input3) Sebuah fungsi dapat menerima input dan mengeluarkan output dengan jumlah variabel sebanyak yang diperlukan. Baris yang merupakan sebuah keterangan untuk memudahkan pembacaan program biasa diberikan tanda “%” pada awal tiap baris. sin(pi/4) ans = 0.7071
  • 9. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 9 Fungsi dapat ditulis dengan trik, dan praktis diperlukan untuk keberhasilan menuliskan sebuah fungsi untuk mendapatkan hasil yang diperlukan. Contoh berikut adalah m-file yaitu add.m yang berisi : Bila ketiga baris perintah ini diberi nama add.m pada direktori Matlab, maka pada file ini dapat dieksekusi pada command line : Polynomials Pada Matlab, sebuah polynomial ditampilkan dengan sebuah vector. Untuk menuliskan sebuah polynomial di dalam matlab dapat dilihat contoh berikut ini : Persamaan : Dalam Matlab ditulis : Matlab dapat mengartikan sebuah vector sepanjang n+1 sebagai deret polynomial sepanjang n. Untuk itu, dapat dilakukan dengan : dipresentasikan dalam Matlab sebagai : y = [1 0 0 0 1] function [var3] = add(var1,var2) %add is a function that adds two numbers var3 = var1+var2; y = add(3,8) x = [1 3 -15 -2 9] x = 1 3 -15 -2 9
  • 10. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 10 Pada polynomial dengan s=2, z = polyval([1 0 0 0 1],2) z = 17 Untuk mencari akar persamaan dari : adalah dengan menuliskan : Untuk mengkalikan dua polynomial : Contoh : Untuk membagi dua polynomial : roots([1 3 -15 -2 9]) ans = -5.5745 2.5836 -0.7951 0.7860 x = [1 2]; y = [1 4 8]; z = conv(x,y) z = 1 6 16 16 [xx, R] = deconv(z,y) xx = 1 2 R = 0 0 0 0
  • 11. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 11 Sebagaimana dapat dilihat, bila untuk menjumlahkan dua polynomial, dengan panjang yang sama, dapat digunakan perintah polyadd, yang sudah dijadikan fungsi di dalam mfile : Matrik Entering matrices into Matlab is the same as entering a vector, except each row of elements is separated by a semicolon (;) or a return: B = [1 2 3 4;5 6 7 8;9 10 11 12] B = 1 2 3 4 5 6 7 8 9 10 11 12 B = [ 1 2 3 4 5 6 7 8 9 10 11 12] B = 1 2 3 4 5 6 7 8 9 10 11 12 Matrices in Matlab can be manipulated in many ways. For one, you can find the transpose of a matrix using the apostrophe key: C = B' z = polyadd(x,y) x = 1 2 y = 1 4 8
  • 12. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 12 C = 1 5 9 2 6 10 3 7 11 4 8 12 It should be noted that if C had been complex, the apostrophe would have actually given the complex conjugate transpose. To get the transpose, use .' (the two commands are the same if the matix is not complex). Now you can multiply the two matrices B and C together. Remember that order matters when multiplying matrices. D = B * C D = 30 70 110 70 174 278 110 278 446 D = C * B D = 107 122 137 152 122 140 158 176 137 158 179 200 152 176 200 224 Another option for matrix manipulation is that you can multiply the corresponding elements of two matrices using the .* operator (the matrices must be the same size to do this). E = [1 2;3 4] F = [2 3;4 5] G = E .* F E = 1 2 3 4
  • 13. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 13 F = 2 3 4 5 G = 2 6 12 20 If you have a square matrix, like E, you can also multiply it by itself as many times as you like by raising it to a given power. E^3 ans = 37 54 81 118 If wanted to cube each element in the matrix, just use the element-by-element cubing. E.^3 ans = 1 8 27 64 You can also find the inverse of a matrix: X = inv(E) X = -2.0000 1.0000 1.5000 -0.5000 or its eigenvalues:
  • 14. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 14 eig(E) ans = -0.3723 5.3723 There is even a function to find the coefficients of the characteristic polynomial of a matrix. The "poly" function creates a vector that includes the coefficients of the characteristic polynomial. p = poly(E) p = 1.0000 -5.0000 -2.0000 Remember that the eigenvalues of a matrix are the same as the roots of its characteristic polynomial: roots(p) ans = 5.3723 -0.3723
  • 15. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 15 Plotting in Matlab Plotting Menggambarkan plotting pada matlab dapat dilakukan dengan mudah. Bila sebuah gelombang sinus akan diplot sesuai fungsi waktu, maka pertama-tama akan dibuat vector waktu (dengan memberikan tanda titik koma, sebagai tanda bahwa tidak semua nilai ditampilkan), maka matlab akan menggambarkan keluarannya. Contoh : One of the most important functions in Matlab is the plot function. Plot also happens to be one of the easiest functions to learn how to use. The basic format of the function is to enter the following command in the Matlab command window or into a m-file. plot(x,y) t=0:0.25:7; y = sin(t); plot(t,y)
  • 16. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 16 This command will plot the elements of vector x on the horizontal axis of a figure, and the elements of the vector y on the vertical axis of the figure. The default is that each time the plot command is issued, the current figure will be erased; we will discuss how to override this below. If we wanted to plot the simple, linear formula: y=3x We could create a m-file with the following lines of code: x = 0:0.1:100; y = 3*x; plot(x,y) which will generate the following plot, One thing to keep in mind when using the plot command is that the vectors x and y must be the same length. The other dimension can vary. Matlab can plot a 1 x n vector versus a n x 1 vector, or a 1 x n vector versus a 2 x n matrix (you will get two lines), as long as n is the same for both vectors. The plot command can also be used with just one input vector. In that case the vector columns are plotted versus their indices (the vector 1:1:n will be used for the horizontal axis). If the input vector contains complex numbers, Matlab plots the real part of each element (on the x-axis) versus the imaginary part (on the y-axis).
  • 17. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 17 Plot aesthetics The color and point marker can be changed on a plot by adding a third parameter (in single quotes) to the plot command. For example, to plot the above function as a red, dotted line, the m-file should be changed to: x = 0:0.1:100; y = 3*x; plot(x,y,'r:') The plot now looks like: The third input consists of one to three characters which specify a color and/or a point marker type. The list of colors and point markers is as follows: y yellow . point m magenta o circle c cyan x x-mark r red + plus g green - solid b blue * star w white : dotted k black -. dashdot -- dashed You can plot more than one function on the same figure. Let's say you want to plot a sine wave and cosine wave on the same set of axes, using a different color and point marker for each. The following m-file could be used to do this:
  • 18. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 18 x = linspace(0,2*pi,50); y = sin(x); z = cos(x); plot(x,y,'r', x,z,'gx') You will get the following plot of a sine wave and cosine wave, with the sine wave in a solid red line and the cosine wave in a green line made up of x's: By adding more sets of parameters to plot, you can plot as many different functions on the same figure as you want. When plotting many things on the same graph it is useful to differentiate the different functions based on color and point marker. This same effect can also be achieved using the hold on and hold off commands. The same plot shown above could be generated using the following m-file: x = linspace(0,2*pi,50); y = sin(x); plot(x,y,'r') z = cos(x); hold on plot(x,z,'gx') hold off Always remember that if you use the hold on command, all plots from then on will be generated on one set of axes, without erasing the previous plot, until the hold off command is issued.
  • 19. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 19 Subplotting More than one plot can be put on the same figure using the subplot command. The subplot command allows you to separate the figure into as many plots as desired, and put them all in one figure. To use this command, the following line of code is entered into the Matlab command window or an m-file: subplot(m,n,p) This command splits the figure into a matrix of m rows and n columns, thereby creating m*n plots on one figure. The p'th plot is selected as the currently active plot. For instance, suppose you want to see a sine wave, cosine wave, and tangent wave plotted on the same figure, but not on the same axis. The following m-file will accomplish this: x = linspace(0,2*pi,50); y = sin(x); z = cos(x); w = tan(x); subplot(2,2,1) plot(x,y) subplot(2,2,2) plot(x,z) subplot(2,2,3) plot(x,w) As you can see, there are only three plots, even though I created a 2 x 2 matrix of 4 subplots. I did this to show that you do not have to fill all of the subplots you have
  • 20. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 20 created, but Matlab will leave a spot for every position in the matrix. I could have easily made another plot using the line subplot(2,2,4) command. The subplots are arranged in the same manner as you would read a book. The first subplot is in the top left corner, the next is to its right. When all the columns in that row are filled, the left-most column on the next row down is filled (all of this assuming you fill your subplots in order i.e. 1, 2, 3,..). One thing to note about the subplot command is that every plot command issued later will place the plot in whichever subplot position was last used, erasing the plot that was previously in it. For example, in the m-file above, if a plot command was issued later in the m-file, it would be plotted in the third position in the subplot, erasing the tangent plot. To solve this problem, the figure should be cleared (using clf), or a new figure should be specified (using figure). Changing the axis Now that you have found different ways to plot functions, you can customize your plots to meet your needs. The most important way to do this is with the axis command. The axis command changes the axis of the plot shown, so only the part of the axis that is desirable is displayed. The axis command is used by entering the following command right after the plot command (or any command that has a plot as an output): axis([xmin, xmax, ymin, ymax]) For instance, suppose want to look at a plot of the function y=exp(5t)-1. If you enter the following into Matlab t=0:0.01:5; y=exp(5*t)-1; plot(t,y)
  • 21. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 21 you should have the following plot: As you can see, the plot goes to infinity. Looking at the y-axis (scale: 8e10), it is apparent that not much can be seen from this plot. To get a better idea of what is going on in this plot, let's look at the first second of this function. Enter the following command into the Matlab command window. axis([0, 1, 0, 50]) and you should get the following plot: Now this plot is much more useful. You can see more clearly what is going on as the function moves toward infinity. You can customize the axis to your needs. When using the subplot command, the axis can be changed for each subplot by issuing an axis command before the next subplot command. There are more uses of the axis command which you can see if you type help axis in the Matlab command window.
  • 22. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 22 Adding text Another thing that may be important for your plots is labeling. You can give your plot a title (with the title command), x-axis label (with the xlabel command), y-axis label (with the ylabel command), and put text on the actual plot. All of the above commands are issued after the actual plot command has been issued. A title will be placed, centered, above the plot with the command: title('title string'). The x-axis label is issued with the following command: xlabel('x-axis string'). The y-axis label is issued with the following command: ylabel('y-axis string'). Furthermore, text can be put on the plot itself in one of two ways: the text command and the gtext command. The first command involves knowing the coordinates of where you want the text string. The command is text(xcor,ycor,'textstring'). To use the other command, you do not need to know the exact coordinates. The command is gtext('textstring'), and then you just move the cross-hair to the desired location with the mouse, and click on the position you want the text placed. To further demonstrate labeling, take the step response plot from above. Assuming that you have already changed the axis, copying the following lines of text after the axis command will put all the labels on the plot: title('step response of something') xlabel('time (sec)') ylabel('position, velocity, or something like that') gtext('unnecessary labeling') The text "unnecessary labeling" was placed right above the position, I clicked on. The plot should look like the following:
  • 23. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 23 Other commands that can be used with the plot command are: • clf (clears the current plot, so it is blank) • figure (opens a new figure to plot on, so the previous figure is saved) • close (closes the current figure window) • loglog (same as plot, except both axes are log base 10 scale) • semilogx (same as plot, except x-axis is log base 10 scale) • semilogy (same as plot, except y-axis is log base 10 scale) • grid (adds grid line to your plot) Of course this is not a complete account of plotting with Matlab, but it should give you a nice start Printing Printing in Matlab is pretty easy. Just follow the steps illustrated below: Macintosh To print a plot or a m-file from a Macintosh, just click on the plot or m-file, select Print under the File menu, and hit return. Windows
  • 24. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 24 To print a plot or a m-file from a computer running Windows, just selct Print from the File menu in the window of the plot or m-file, and hit return. Unix To print a plot on a Unix workstation enter the command: print -P<printername> If you want to save the plot and print it later, enter the command: print plot.ps Sometime later, you could print the plot using the command "lpr -P plot.ps" If you are using a HP workstation to print, you would instead use the command "lpr -d plot.ps" To print a m-file, just print it the way you would any other file, using the command "lpr -P <name of m-file>.m" If you are using a HP workstation to print, you would instead use the command "lpr -d plot.ps<name of m-file>.m"
  • 25. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 25 Matlab Commands List The following list of commands can be very useful for future reference. Use "help" in Matlab for more information on how to use the commands. In these tutorials, we use commands both from Matlab and from the Control Systems Toolbox, as well as some commands/functions which we wrote ourselves. For those commands/functions which are not standard in Matlab, we give links to their descriptions. For more information on writing Matlab functions, see the function page. Note:Matlab commands from the control system toolbox are highlighted in red. Non-standard Matlab commands are highlighted in green. Command Description abs Absolute value acker Compute the K matrix to place the poles of A-BK, see also place axis Set the scale of the current plot, see also plot, figure bode Draw the Bode plot, see also logspace, margin, nyquist1 c2dm Continuous system to discrete system clf Clear figure (use clg in Matlab 3.5) conv Convolution (useful for multiplying polynomials), see also deconv ctrb The controllability matrix, see also obsv deconv Deconvolution and polynomial division, see also conv det Find the determinant of a matrix dimpulse Impulse response of discrete-time linear systems, see also dstep dlqr Linear-quadratic requlator design for discrete-time systems, see also lqr dlsim Simulation of discrete-time linear systems, see also lsim dstep Step response of discrete-time linear systems, see also stairs eig Compute the eigenvalues of a matrix eps Matlab's numerical tolerance feedback Feedback connection of two systems.
  • 26. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 26 figure Create a new figure or redefine the current figure, see also subplot, axis for For, next loop format Number format (significant digits, exponents) function Creates function m-files grid Draw the grid lines on the current plot gtext Add a piece of text to the current plot, see also text help HELP! hold Hold the current graph, see also figure if Conditionally execute statements imag Returns the imaginary part of a complex number, see also real impulse Impulse response of continuous-time linear systems, see also step, lsim, dlsim input Prompt for user input inv Find the inverse of a matrix jgrid Generate grid lines of constant damping ratio (zeta) and settling time (sigma), see also sgrid, sigrid, zgrid legend Graph legend length Length of a vector, see also size linspace Returns a linearly spaced vector lnyquist1 Produce a Nyquist plot on a logarithmic scale, see also nyquist1 log natural logarithm, also log10: common logarithm loglog Plot using log-log scale, also semilogx/semilogy logspace Returns a logarithmically spaced vector lqr Linear quadratic regulator design for continuous systems, see also dlqr lsim Simulate a linear system, see also step, impulse, dlsim. margin Returns the gain margin, phase margin, and crossover frequencies, see also bode norm Norm of a vector nyquist1 Draw the Nyquist plot, see also lnyquist1. Note this command was
  • 27. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 27 written to replace the Matlab standard command nyquist to get more accurate Nyquist plots. obsv The observability matrix, see also ctrb ones Returns a vector or matrix of ones, see also zeros place Compute the K matrix to place the poles of A-BK, see also acker plot Draw a plot, see also figure, axis, subplot. poly Returns the characteristic polynomial polyadd Add two different polynomials polyval Polynomial evaluation print Print the current plot (to a printer or postscript file) pzmap Pole-zero map of linear systems rank Find the number of linearly independent rows or columns of a matrix real Returns the real part of a complex number, see also imag rlocfind Find the value of k and the poles at the selected point rlocus Draw the root locus roots Find the roots of a polynomial rscale Find the scale factor for a full-state feedback system set Set(gca,'Xtick',xticks,'Ytick',yticks) to control the number and spacing of tick marks on the axes series Series interconnection of Linear time-independent systems sgrid Generate grid lines of constant damping ratio (zeta) and natural frequency (Wn), see also jgrid, sigrid, zgrid sigrid Generate grid lines of constant settling time (sigma), see also jgrid, sgrid, zgrid size Gives the dimension of a vector or matrix, see also length sqrt Square root ss Create state-space models or convert LTI model to state space, see also tf ss2tf State-space to transfer function representation, see also tf2ss ss2zp State-space to pole-zero representation, see also zp2ss
  • 28. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 28 stairs Stairstep plot for discreste response, see also dstep step Plot the step response, see also impulse, lsim, dlsim. subplot Divide the plot window up into pieces, see also plot, figure text Add a piece of text to the current plot, see also title, xlabel, ylabel, gtext tf Creation of transfer functions or conversion to transfer function, see also ss tf2ss Transfer function to state-space representation, see also ss2tf tf2zp Transfer function to Pole-zero representation, see also zp2tf title Add a title to the current plot wbw Returns the bandwidth frequency given the damping ratio and the rise or settling time. xlabel/ylabel Add a label to the horizontal/vertical axis of the current plot, see also title, text, gtext zeros Returns a vector or matrix of zeros zgrid Generates grid lines of constant damping ratio (zeta) and natural frequency (Wn), see also sgrid, jgrid, sigrid zp2ss Pole-zero to state-space representation, see also ss2zp zp2tf Pole-zero to transfer function representation, see also tf2zp
  • 29. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 29 Modeling Tutorial Matlab can be used to represent a physical system or a model. To begin with, let's start with a review of how to represent a physical system as a set of differential equations. Train system In this example, we will consider a toy train consisting of an engine and a car. Assuming that the train only travels in one direction, we want to apply control to the train so that it has a smooth start-up and stop, along with a constant-speed ride. The mass of the engine and the car will be represented by M1 and M2, respectively. The two are held together by a spring, which has the stiffness coefficient of k. F represents the force applied by the engine, and the Greek letter, mu (which will also be represented by the letter u), represents the coefficient of rolling friction. Photo courtesy: Dr. Howard Blackburn Free body diagram and Newton's law The system can be represented by following Free Body Diagrams. From Newton's law, you know that the sum of forces acting on a mass equals the mass times its acceleration. In this case, the forces acting on M1 are the spring, the friction and the force applied by the engine. The forces acting on M2 are the spring and the friction. In the vertical direction, the gravitational force is canceled by the normal force applied by the ground, so that there will be no acceleration in the vertical direction. The equations of motion in the horizontal direction are the followings:
  • 30. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 30 State-variable and output equations This set of system equations can now be manipulated into state-variable form. Knowing state-variables are X1 and X2 and the input is F, state-variable equations will look like the following: Let the output of the system be the velocity of the engine. Then the output equation will become: 1. Transfer function To find the transfer funciton of the system, first, take Laplace transforms of above state- variable and output equations. Using these equations, derive the transfer function Y(s)/F(s) in terms of constants. When finding the transfer function, zero initial conditions must be assumed. The transfer function should look like the one shown below.
  • 31. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 31 2. State-space Another method to solve the problem is to use the state-space form. Four matrices A, B, C, and D characterize the system behavior, and will be used to solve the problem. The state-space form that were manipulated from the state-variable and the output equations is shown below. Matlab representation Now we will show you how to enter the equations derived above into an m-file for Matlab. Since Matlab can not manipulate symbolic variables, let's assign numerical values to each of the variables. Let • M1 = 1 kg • M2 = 0.5 kg • k = 1 N/sec • F= 1 N • u = 0.002 sec/m • g = 9.8 m/s^2 Create an new m-file and enter the following commands. M1=1; M2=0.5;
  • 32. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 32 k=1; F=1; u=0.002; g=9.8; Now you have one of two choices: 1) Use the transfer function, or 2) Use the state- space form to solve the problem. If you choose to use the transfer function, add the following commands onto the end of the m-file which you have just created. num=[M2 M2*u*g 1]; den=[M1*M2 2*M1*M2*u*g M1*k+M1*M2*u*u*g*g+M2*k M1*k*u*g+M2*k*u*g]; If you choose to use the state-space form, add the following commands at the end of the m-file, instead of num and den matrices shown above. A=[ 0 1 0 0; -k/M1 -u*g k/M1 0; 0 0 0 1; k/M2 0 -k/M2 -u*g]; B=[ 0; 1/M1; 0; 0]; C=[0 1 0 0]; D=[0]; See the Matlab basics tutorial to learn more about entering matrices. Continue solving the problem Now, you are ready to obtain the system output (with an addition of few more commands). It should be noted that many operations can be done using either the transfer function or the state-space model. Furthermore, it is simple to transfer between the two if the other form of representation is required. If you need to learn how to convert from one representation to the other, click Conversion.
  • 33. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 33 Perhitungan dan Pemrograman dengan MATLAB 2.1. Matematika Sederhana Seperti kalkulator, MATLAB dapat melakukan perhitungan matematika sederhana. Contoh : Lakukan perhitungan di bawah ini dengan menggunakan MATLAB !!! “Wati berbelanja ke toko buku membeli 10 buku tulis @Rp 1500, 1 buah penghapus pinsil Rp 1000, dan 2 isi bolpoint @ Rp 800,-“ Maka yang harus dibayarkan oleh Wati adalah : EDU>>10*1500+1000+2*800 ans = 17600 Dapat pula dihitung dengan menuliskan program : EDU>> buku=10 buku = 10 EDU>> penghapus=1 penghapus = 1 EDU>> isi = 2; EDU>> bayar = buku*1500 + penghapus * 1000 + isi * 800 bayar = 17600 MATLAB tidak memperhatikan spasi, untuk sebagian besar, dan perkalian diprioritaskan terlebih dahulu dari penjumlahan. Juga perlu diketahui, MATLAB menyebut hasil sebagai ans (singkatan dari answer). Pada penjumlahan dan perkalian, MATLAB menggunakan operasi aritmatik dasar berikut ini :
  • 34. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 34 Operasi Rumus Aritmatik Simbol Penulisan Penjumlahan a + b + a + b Pengurangan a – b - a – b Perkalian a x b * a * b Pembagian a : b / atau a / b atau b a Pangkat ab ^ a^b Urutan operasi yang akan dilakukan adalah dengan menggunakan aturan yang biasa digunakan, yaitu perhitungan dihitung dari kiri ke kanan, operasi pangkat merupakan urutan pertama, diikuti dengan perkalian dan pembagian, dan terakhir adalah penjumlah dan pengurangan. Untuk operasi yang dilakukan dalam tanda kurung, maka operasi itu yang pertama akan dilakukan dari operasi yang ada di luarnya.
  • 35. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 35 2.2. Komentar dan Pemberian Tanda Baca Semua huruf di belakang tanda % dibaca sebagai pernyataan bebas (tidak mempengaruhi program) Contoh : EDU>> buku = 10 % jumlah dari buku yang dibeli buku = 10 Beberapa perintah dapat diletakkan pada satu baris bila dipisah dengan koma, atau titik koma. Contoh : EDU>> buku = 10, penghapus = 1; isi = 2 buku = 10 isi = 2 2.3. Bilangan Komplek Salah satu dari kelebihan MATLAB adalah tidak diperlukannya penanganan khusus untuk bilangan komplek. Bilangan komplek ditampilkan oleh MATLAB dengan beberapa cara. Contoh : EDU>> c1=1-2i % i menunjukkan bagian imajiner c1 = 1.0000 – 2.0000i EDU>> c1=1-2j % j juga bisa digunakan c1 = 1.0000 – 2.0000i EDU>> c2=3*(2-sqrt(-1)*3) c2 = 6.0000 – 9.0000i EDU>> c3=sqrt(-2) c3 = 0 + 1.4142 i dan seterusnya.
  • 36. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 36 2.4. Fungsi-fungsi Matematika yang umum digunakan Pernyataan Fungsi abs(x) nilai absolut atau besar bilangan komplek acos(x) invers cosinus acosh(x) invers cosinus hyperbolis angle(x) sudut 4 kuadrant dari komplek asin(x) invers sinus asinh(x) invers sinus hyperbolis atan(x) invers tangen atan2(x,y) invers tangen 4 kuadrant atanh(x) invers tangen hyperbolis ceil(x) gerak siklus plus tak hingga conj(x) konjugasi komplek cos(x) cosinus cosh(x) cosinus hyperbolis exp(x) eksponensial (ex ) fix(x) gerak siklus nol floor(x) gerak siklus minus tak hingga gcd(x,y) pembagi terbesar dari bilangan bulat x dan y imag(x) bagian bilangan imajiner lcm(x,y) perkalian terkecil dari bilangan bulat x dan y log(x) logaritma alami log10(x) logaritma biasa real(x) bagian bilangan real rem(x,y) sisa dari pembagian (rem (x,y) memberikan sisa dari x/y) round(x) bilangan bulat terdekat dari siklus lingkar sign(x) fungsi signum sin(x) sinus sinh(x) sinus hyperbolis sqrt(x) akar persamaan tan(x) tangen tanh(x) tangen hyperbolic
  • 37. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 37 Latihan-latihan Soal dengan MATLAB Latihan 1 : Perhitungan dengan Matrik Didalam menulis suatu bentuk matrik, setiap kolom dipisahkan dengan matrik, dan setiap baris dipisahkan dengan tanda titik koma. Contoh : Matrik G = 1 2 3 4 5 6 7 8 9 Maka ditulis : EDU>> g=[1 2 3;4 5 6;7 8 9] g = 1 2 3 4 5 6 7 8 9 atau : EDU>> g=[1 2 3 4 5 6 7 8 9] g = 1 2 3 4 5 6 7 8 9 EDU>>size(g) % ordo dari matrik a ans = 22 Fungsi lain matriks yang harus diketahui : inv(a) ∗ inverse dari matrik a transpose(a) ∗ transpose dari matrik a
  • 38. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 38 det(a) ∗ determinan dari matrik a Soal Latihan : 1. A = 1 2 3 4 a. Tulislah perintah dari MATLAB prompt untuk matrik A b. Hitunglah transpose dari matrik A c. Hitunglah determinan dari matrik A d. Hitunglah invers dari matrik A e. Buktikan bahwa A-1 =1/det * A? f. Buktikan bahwa A x A-1 = I
  • 39. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 39 Latihan 2 : Transfer Function Untuk menuliskan fungsi dari diagram blok di atas dan kemudian menuliskannya setelah diberi umpan balik H(s)=1 adalah : Bila suatu transfer function (fungsi Laplace) akan diubah ke dalam bentuk perhitungan ruang keadaan (state space equation) untuk diagram blok di atas di mana x(t) = ax(t) + bu(t) y(t) = cx(t) + du(t) maka ditulis program sebagai berikut : Buatlah m.file dari kedua program di atas dan lihatlah hasilnya S + 2 S2 + 2S + 1 num=[1 2] den=[1 2 1] printsys(num,den) [a,b,c,d]=ss2tf(num,den) num=[1 2] den=[1 2 1] printsys(num,den) [numcl,dencl]=cloop(num,den) printsys(numcl,dencl)
  • 40. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 40 Fungsi – fungsi lain yang harus diketahui : [num,den]=ss2tf(a,b,c,d) ∗ untuk mengubah dari state space menjadi transfer function [nump,denp]=parallel(num1,den1,num2,den2) ∗ menghitung paralel dari dua fungsi [nums,dens]=series(num1,den1,num2,den2) ∗ menghitung seri dari dua fungsi [numf,denf]=feedback(num1,den1,numh,denh) ∗ menghitung fungsi alih dengan umpan balik fungsi H(s) step(num,den) ∗ melukis tanggapan waktu dari fungsi alih loop tertutup figure ∗ untuk membuat window gambar baru Tugas : Fungsi 1 : S + 1 ( S + 3 )( S + 5 ) Fungsi 2 : S + 6 S + 10 a. Hitunglah fungsi alih lingkar tertutup dari fungsi 1 ( H(s) = 1 ) b. Hitunglah fungsi alih dari fungsi 1 dan fungsi 2 yang dihubung paralel. c. Hitunglah fungsi alih dari fungsi 1 dan fungsi 2 yang dihubung seri. d. Hitunglah fungsi alih dengan fungsi 2 sebagai umpan balik. e. Hitung state space equation dari fungsi 1 f. Gambarkan fungsi tanggapan waktu dari fungsi 1 g. Gambarkan fungsi tanggapan waktu dari fungsi 2 Save dengan nama “Latih1.m”
  • 41. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 41 Latihan 3 : Fungsi Tanggapan Waktu & Tempat Kedudukan Akar 4.3.1. Fungsi Tanggapan Waktu 4.3.1.1. Sistem Orde Satu Dengan masukan R(s)=1/2, sistem orde satu dapat dinyatakan dengan : C(s) = R(s)G(s) = a . s(s+a) Invers sistem di atas memberikan tanggapan step : c(t) = cf(t) + cn(t) = 1 – e-at Dari persamaan di atas terlihat pentingnya parameter a, satu-satunya parameter yang berpengaruh terhadap tanggapan transien. Jika t = 1/a e-at ⏐t=1/1 = e-1 = 0.37 atau x(t) = 1-e-at ⏐t=1/a = 1- 0.37 = 0.63 ☺ Konstanta Waktu (Time Constant) Konstanta waktu adalah waktu yang dibutuhkan sistem untuk mencapai harga 63% dari harga akhir. ☺ Rise Time, Tr Rise Time didefinisikan sebgai waktu yang dibutuhkan untuk beranjak dari titik 10% hingga 90% dari harga akhir. Rumus Tr = Tr = 2,2 2ζωn ☺ Settling Time, Ts Settling time didefinisikan sebagai waktu yang dibutuhkan tanggapan untuk mencapai 98% dari harga akhir. Rumus settling time : Ts = 4 2ζωn 4.3.1.2. Sistem Orde Dua Berbeda dengan sistem orde pertama, sistem orde dua mempunyai tingkat kompleksitas yang lebih besar, lebih banyak parameter yang harus dianalisa dan diamati untuk dapat menentukan tanggapan sistem.
  • 42. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 42 Tanggapan pada sistem orde dua ada empat macam : Tanggapan teredam lebih Tanggapan kurang teredam Tanggapan osilasi Tanggapan teredam kritis Ada beberapa istilah yang biasa digunakan untuk menyatakan sistem- sistem berorde dua ini, yang pertama adalah frekuensi alami. Frekuensi alami ωn adalah frekuensi osilasi sistem tanpa peredaman. Kedua, adalah damping ratio ζ. Damping ratio ini didefinisikan sebagai perbandingan antara frekuensi pengurangan eksponensial dengan frekuensi alaminya. Untuk memperjelas konsep, perhatikan sistem umum berikut : G(s) = ωn 2 . s2 + 2ζωns + ωn 2 ☺ Peak Time, Tp Peak time adalah waktu yang dibutuhkan untuk mencapai puncak pertama atau puncak maksimum. Nilai peak time dirumuskan dengan : 2 1 ζω π − = n Tp ☺ Percent Overshoot, %OS Percent overshoot adalah perbandingan selisih harga maksimum dengan harga akhir sistem (dalam persen). Rumusan untuk mendapatkan nilainya adalah : )100/(%ln 100/ln(% 22 OS OS + − = π ζ ☺ Settling Time, Ts Settling time adalah waktu yang dibutuhkan transien osilasi teredam untuk berada pada ± 2% harga keadaan tunak. Rumus Ts : n sT ζω 4 =
  • 43. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 43 ☺ Rise Time, Tr Rise time adalah waktu yang dibutuhkan bentuk gelombang untuk beranjak dari harga 10% ke 90% harga akhir. Nilai rise time secara analitis tidak dapat didapat. n d d tgTr ζω ω ω − = −11 dimana 2 1 ζωω −= nd Penulisan perhitungan-perhitungan di atas beberapa diantaranya bila ditulis dalam MATLAB adalah sebagai berikut : 4.3.2. Tempat Kedudukan Akar Tempat Kedudukan Akar adalah metoda yang cukup efektif dalam perancangan dan analisis stabilitas dan tanggapan transien. TKA dapat digunakan secara kualitatif menerangkan unjuk kerja sebuah sistem dengan berbagai variasi perubahan parameter. Sebagai contoh, efek num = den = finalvalue = polyval(num,0)/polyval(den,0) [y,x,t]=step(num,den); [Y,k]=max(y); %menghitung time to peak (tp) timetopeak=t(k) %menghitung percentovershoot percentovershoot=100*(Y-finalvalue)/finalvalue %menghitung rise time (tr) n=1; while y(n)<0.1*finalvalue,n=n+1;end m=1; while y(m)<0.9*finalvalue,m=m+1;end risetime=t(m)-t(n) %menghitung settling time (ts) l=length(t); while(y(l)>0.98*finalvalue)&(y(l)<1.02*finalvalue) l=l-1; end settlingtime=t(l)
  • 44. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 44 variasi penguatan percent overshoot, settling time, dan peak time. Disamping tanggapan transien, TKA dapat memberikan informasi grafis tentang stabilitas sebuah sistem. Dapat terlihat secara jelas range stabilitas, range ketidakstabilan dan kondisi yang menyebabkan sistem menuju osilasi. ☺ Aturan Perancangan TKA Beberapa istilah yang berpengaruh dalam perancangan TKA : 1. Jumlah percabangan 2. Simetri 3. Segmen sumbu real 4. Titik awal dan titik akhir 5. Beberapa aturan tambahan. Untuk melukiskan tempat kedudukan akar dan menentukan k dan poles dimana : k = -den(p)/num(p) dan poles adalah kutub-kutub dari persamaan sistem lingkar terbuka, di dalam MATLAB adalah : Tugas : Sebuah sistem memiliki persamaan sebagai berikut : num = den = wn = damping = rlocus(num,den) sgrid(damping,wn) axis([-2 2 –6 6]) [k,poles]=rlocfind(num,den) 1 S2 + 2S + 1 C(s) R(s)
  • 45. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 45 a. Tentukan Tr, Ts, Td, %OS, ωn b. Gambarkan Fungsi Tanggapan waktunya c. Tentukan k dan kutub-kutub dari persamaan di atas d. Lukiskan Tempat Kedudukan akarnya
  • 46. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 46 Latihan 4 : Transfer Fungsi Kontinyu – Diskrit, dan Fungsi Tanggapan Waktu Diskrit dengan metode ZOH dan FOH 4.4.1. Sinyal Waktu Diskrit Sinyal waktu diskrit timbul bila sistim melibatkan suatu operasi pencuplikan dari sinyal waktu kontinyu, atau bila sistim melibatkan suatu proses iteratif yang dibawa oleh komputer digital. Urutan dari nilai atau angka biasanya ditulis sebagai x(k), dimana k menunjukkan urutan nilai atau angka muncul pada deret, contoh x(0), x(1), x(2), … Bila sinyal waktu kontinyu dicuplik, periode pencuplikan T menjadi parameter yang penting 4.4.2. Impulse Sampling Suatu sampling mempunyai periode T, dan duration sampling sangat singkat. Sampling ditimbulkan oleh sampler dari fungsi yang kontinyu, menjadi pulsa train, misal : t=0, T, 2T, … dengan T, perioda sampling. Data Hold Circuit, mengkonversikan sample data ke dalam sinyal yang kontinyu. Data hold adalah proses pembangkitan sinyal waktu kontinyu h(t) dari deret waktu diskrit x(kT) Sinyal h(t) selama interval waktu kT ≤ t ≤ (k+1)T dapat didekati oleh polinomial dalam τ : n(kT+τ) = anτn + an-1τn-1 + … + a1τ + a0 untuk 0≤τ≤t, h(kT) = x(kT) 4.4.3. Fungsi Alih Rangkaian Hold Fungsi alih ZOH : Gh0(s) = s sT− −ε1 dengan ZOH, integrator reset ke nol setelah satu periode sampling. Fungsi alih FOH : Gh1(s) = T Ts s sT 11 2 + ⎟⎟ ⎠ ⎞ ⎜⎜ ⎝ ⎛ − − ε
  • 47. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 47 Keluaran h(t) dari FOH adalah garis lurus yang merupakan extrapolasi dari 2 nilai sampling. Dengan Matlab, semua ketentuan di atas dapat diperoleh dengan cara yang jauh lebih mudah. Seperti contoh berikut ini :
  • 48. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 48 Tugas : Sebuah sistem memiliki persamaan sebagai berikut : a. Tentukan transformasi Z dengan (Ts = 0.3) loop tertutup dari fungsi di atas Ts= 0.5; %periode pencuplikan num=[1]; den=[1 8 4]; printsys(num,den) %sistem kontinyu loop terbuka [numc,denc]=cloop(num,den); printsys(numc,denc) %sistim kontinyu loop tertutup [numd,dend]=c2dm(numc,denc,Ts); %transformasi kontinyu-diskrit printsys(numd,dend,'z') %fungsi diskrit subplot(121), step(numc,denc) subplot(122), dstep(numd,dend) figure [ndf,ddf]=c2dm(numc,denc,Ts,'foh'); %pencuplikan dengan first order hold printsys(ndf,ddf,'z') [ndz,ddz]=c2dm(numc,denc,Ts,'zoh'); %pencuplikan dengan zero order hold printsys(ndz,ddz,'z') subplot(121), dstep(ndf,ddf) subplot(122), dstep(ndz,ddz) 1 S2 + 2S + 1 C(s) R(s)
  • 49. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 49 b. Buatlah grafik tanggapan waktu kontinyu c. Buatlah grafik tanggapan waktu diskritnya d. Buatlah fungsi pencuplikan dengan cara ZOH dan grafiknya e. Buatlah fungsi pencuplikan dengan cara FOH dan grafiknya.
  • 50. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 50 Latihan 5 : Kriteria Kestabilan Menurut Jury-Test Suatu sistem dengan persamaan karakteristik P(z) = aoZn + a1Zn-1 + … an-1z + an Sistem stabil bila memenuhi semua kondisi di bawah ini : 1. ⏐an⏐ < ⏐a0⏐ 2. P(z)⏐z=1 > 0 3. P(z)⏐z=-1 untukngenp iluntuknganj 0 0 > <〈 4. ⏐bn-1⏐ >⏐b0⏐ ⏐cn-2⏐ >⏐c0⏐ ⏐dn-3⏐ >⏐d0⏐ … ⏐q2⏐ > ⏐q0⏐ dimana : bk = 10 1 + −− k knn aa aa k = 0,1,2,3,…,n-1 ck = 10 21 + −−− k knn bb bb k = 0,1,2,3,…,n-2 dk = 10 22 + −−− k knn cc cc k = 0,1,2,3,…,n-3 … qk = 10 23 + − k k pp pp k = 0,1,2 Baris terakhir dari tabel terdiri dari 3 elemen (untuk sistem order-2, 2n-3 = 1 dan tabel Jury hanya berisi satu baris yang terdiri dari tiga elemen. Elemen-elemen dari baris genap adalah reverse dari peletakan elemen- elemen baris ganjil. Contoh dari penulisan program untuk menguji suatu sistim dengan orde 4 adalah :
  • 51. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 51 %PENGUJIAN KESTABILAN SISTIM DISKRIT ORDE 4 %DENGAN METODE JURY'S TEST clear N=5; disp('Orde sistem = ') for k=1:5 kt=k-1 a(k)=input ('Masukkan harga a =') end pst=polyval(a,1) pmt=polyval(a,-1) for k=4:-1:1 matrikb=[a(N) a(N-k);a(1) a(k+1)] b(k)=det(matrikb) end for k=3:-1:1 matrikc=[b(N-1) b(N-1-k);b(1) b(k+1)] c(k)=det(matrikc) end if abs(a(5))<abs(a(1)) s1='Y' else s1='N' end if pst>0 s2='Y' else s2='N' end if pmt>0 s3='Y' else s3='N' end if abs(b(4))>abs(b(1)) s4a='Y' else s4a='N' end if abs(c(3))>abs(c(1)) s4b='Y' else s4b='N' end if s1&s2&s3&s4a&s4b=='Y' sistim='Stabil' else sistim='Tidak stabil' end
  • 52. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 52 Contoh : Untuk menguji suatu sistim orde 4 yang memiliki persamaan karakteristik = P(z)=z4 - 1.2z3 + 0.07z2 + 0.3z - 0.08 adalah : EDU» Tan_Jury4 Orde sistem = kt = 0 Masukkan harga a =1 a = 1
  • 53. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 53 kt = 1 Masukkan harga a =-1.2 a = 1.0000 -1.2000 kt = 2 Masukkan harga a =.07 a = 1.0000 -1.2000 0.0700 kt = 3 Masukkan harga a =.3 a = 1.0000 -1.2000 0.0700 0.3000 kt =
  • 54. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 54 4 Masukkan harga a =-0.08 a = 1.0000 -1.2000 0.0700 0.3000 -0.0800 P(z)=z4 - 1.2z3 + 0.07z2 + 0.3z - 0.08 pst = 0.0900 P(1) = 0.09 pmt = 1.8900 P(-1) = 1.89 matrikb = -0.0800 1.0000 1.0000 -0.0800 b = 0 0 0 -0.9936
  • 55. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 55 matrikb = -0.0800 -1.2000 1.0000 0.3000 b = 0 0 1.1760 -0.9936 matrikb = -0.0800 0.0700 1.0000 0.0700 b = 0 -0.0756 1.1760 -0.9936 matrikb = -0.0800 0.3000 1.0000 -1.2000 b = -0.2040 -0.0756 1.1760 -0.9936 b0 b1 b2 b3 matrikc = -0.9936 -0.2040
  • 56. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 56 -0.2040 -0.9936 c = 0 0 0.9456 matrikc = -0.9936 -0.0756 -0.2040 1.1760 c = 0 -1.1839 0.9456 matrikc = -0.9936 1.1760 -0.2040 -0.0756 c = 0.3150 -1.1839 0.9456 c0 c1 c2 s1 = Y
  • 57. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 57 s2 = Y s3 = Y s4a = Y s4b = Y sistim = Stabil
  • 58. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 58 Latihan 6 : Fungsi Tanggapan Frekuensi Bode Plot Gambar-gambar Bode melukiskan kestabilan relatif sebuah sistem. Dalam kenyataannya, margin fasa dan margin gain seringkali didefinisikan dalam istilah-istilah gambar Bode. Ukuran-ukuran kestabilan relatif ini dapat ditentukan untuk sebuah sistem tertentu dengan suatu usaha menghitung yang minimum dengan menggunakan gambar-gambar Bode, khususnya untuk hal-hal di mana tersedia data tanggapan frekuensi dari percobaan. Magnituda ⏐P(jω)⏐ dari setiap fungsi P(jω) untuk setiap harga ω digambarkan pada suatu skala logaritmik dalam satuan-satuan desibel dimana, dB ≡ 20 log10 ⏐P(jω)⏐ Karena desibel merupakan suatu satuan logaritmik, magnituda db dari sebuah fungsi tanggapan frekuensi yang terdiri dari suatu hasilkali suku- suku adalah sama dengan jumlah magnituda db dari masing-masing suku. Jadi bila digunakan skala logaritmik, gambar magnituda dari sebuah fungsi tanggapan frekuensi yang dapat dinyatakan sebagai hasil kali lebih dari satu suku dapat diperoleh dengan menjumlahkan masing-masing gambar magnituda db untuk setiap suku hasilkali. Gambar magnituda db versus logω disebut gambar magnituda Bode, dan gambar sudut fasa versus logω adalah gambar sudut fasa Bode. Dalam kepustakaan kadang-kadang gambar magnituda Bode disebut gambar Log- modulus. Bentuk Bode untuk fungsi : ))...()(( ))...()(( )( 21 21 n m n pspspss zszszsK sG +++ +++ = dimana m adalah bilangan bulat tak negatif, diperoleh dengan menguraikan semua z dan p dan menyusunnya kembali dalam bentuk : ωjs pspspss zszszsK sG n m n → +++ +++ = )(...)()( (...)()( )( 21 )21 Pengubahan tanggapan magnitudo ke dalam dB menghasilkan
  • 59. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 59 20 log ⏐G(jω)⏐= 20 log K + 20 log ⏐(s+z1)⏐ + 20 log ⏐(s+z2)⏐ +… -20 log ⏐(sm )⏐ + 20 log ⏐(s+p1)⏐- … ⏐s → jω Sementara fasa dari fungsi adalah 1/sm dimana s= jω adalah : [ ])(arg ωjP Contoh program dengan Matlab untuk membuat Bode Plot dari suatu sistim dengan persamaan karakteristik : )10)(15.0( )22.0(*10 )( 2 2 +++ ++ = sss ss sF adalah : Bode representation The Bode plots take each one of the points on the above plot and breaks it down into magnitude and phase. The magnitude is then plotted as gain in decibels and the phase is plotted in degrees. The frequency (on the independent axis) is plotted on a logarithmic scale. Let's take a look at the Bode plots for this function and see if our answers match. bode(num,den) % Sistem yang diberikan num=10*[1 0.2 2]; den=conv([1 0.5 1],[1 10]);%(s^2+0.5s+1)(s+10) disp('Persamaan sistem =') printsys(num,den,'s') % Diskrit dari Sistem dengan Zero Order Hold Ts=0.3 [numd,dend]=c2dm(num,den,Ts,'zoh'); %Contoh membuat Bode dari Sistem bode(num,den) dbode(numd,dend,Ts) Title('Contoh Bode Plot') xlabel('Frekuensi (rad/sec)')
  • 60. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 60 If you look at the plots at a frequency of 3rad/s you will see the magnitude is a little over 2.5 dB and the phase is around 140 degrees. This agrees with our previous results. Tugas : Sebuah sistem memiliki persamaan karakteristik sebagai berikut : )5)(12( )13.0(*15 )( 2 2 +++ ++ = sss ss sF Buatlah Bode Plot dari fungsi tersebut Nyquist Plotting Frequency Response In order to illustrate the plotting of G(jw), we will generate our own plot of G(j*w)and compare it with the Bode plots and the Nyquist diagram. If we run the following m-file, we will see the points that comprise G(jw), in particular the point corresponding to G(j*3). %define the transfer function num = conv([1,4],[1 6]); den = conv([1,-3],[1 -5]);
  • 61. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 61 %create a frequency vector clf w = logspace(-1,2,100); hold on %plot a '+' for each point corresponding to G(jw) for i = 1:100 plot(polyval(num,j*w(1,i))/polyval(den, j*w (1,i)), '+') end %plot a green 'X' for frequency of 3rad/s plot(polyval(num,j*3)/polyval(den, j*3), 'xg') %plot vector from origin to this point n= polyval(num,j*3)/polyval(den, j*3); x = [0,real(n)]; y = [0,imag(n)]; plot(x,y, '-g') %find magnitude and phase Mag = abs(n); Phase = 180 +360*atan(imag(n)/real(n))/(2*pi); %find gain Gain = 20*log10(Mag); grid Mag, Phase, Gain The image should look similar to this: Please note that each yellow cross represents the transfer function evaluated at a specific frequency and that only positive frequencies are used. Also note the point
  • 62. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 62 and vector associated with a frequency of 3 rad/s (green). In the Matlab command window, you should see the Magnitude, Phase, and Gain (in dB) associated with this vector: Note: a decibel is defined as 20*log10 ( |G(j*w| ) Mag = 1.3558 Phase = 139.3987 Gain = 2.6440 Now that we know where Bode plots come form, let's see where Nyquist plots come from. The Nyquist diagram is basically a plot of G(j*w). However, both positive and negative frequencies of the contour we showed previously are taken into account. Let's plot the Nyquist diagram on top of our G(j*w) plot (this time, we will include the negative frequencies as well). %define the transfer function num = conv([1,4],[1 6]); den = conv([1,-3],[1 -5]); %create a frequency vector similar to the one described above w = logspace(-1,2,100); negw = -1*w; clf hold on %plot a '+' for each point corresponding to G(jw) for i = 1:100 plot(polyval(num,j*w(1,i))/polyval(den, j*w (1,i)), '+') plot(polyval(num,j*negw(1,i))/polyval(den, j*negw (1,i)), '+') end %draw Nyquist diagram on top to compare nyquist(num,den) hold off
  • 63. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 63 A perfect match! Also note that the negative frequencies produce a mirror image across the real axis of the positive frequency response.
  • 64. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 64 Gain and Phase Margin Let's say that we have the following system: where K is a variable (constant) gain and G(s) is the plant under consideration. The gain margin is defined as the change in open loop gain required to make the system unstable. Systems with greater gain margins can withstand greater changes in system parameters before becoming unstable in closed loop. Keep in mind that unity gain in magnitude is equal to a gain of zero in dB. The phase margin is defined as the change in open loop phase shift required to make a closed loop system unstable. The phase margin also measures the system's tolerance to time delay. If there is a time delay greater than 180/Wpc in the loop (where Wpc is the frequency where the phase shift is 180 deg), the system will become unstable in closed loop. The time delay can be thought of as an extra block in the forward path of the block diagram that adds phase to the system but has no effect the gain. That is, a time delay can be represented as a block with magnitude of 1 and phase w*time_delay (in radians/second). For now, we won't worry about where all this comes from and will concentrate on identifying the gain and phase margins on a Bode plot: The phase margin is the difference in phase between the phase curve and -180 deg at the point corresponding to the frequency that gives us a gain of 0dB (the gain cross over frequency, Wgc). Likewise, the gain margin is the difference between the magnitude curve and 0dB at the point corresponding to the frequency that gives us a phase of -180 deg (the phase cross over frequency, Wpc).
  • 65. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 65 One nice thing about the phase margin is that you don't need to replot the Bode in order to find the new phase margin when changing the gains. If you recall, adding gain only shifts the magnitude plot up. This is the equivalent of changing the y-axis on the magnitude plot. Finding the phase margin is simply the matter of finding the new cross-over frequency and reading off the phase margin. For example, suppose you entered the command bode(50,[1 9 30 40]). You will get the following bode plot: You should see that the phase margin is about 100 degrees. Now suppose you added a gain of 100, by entering the command bode(100*50,[1 9 30 40]). You should get the following plot (note I changed the axis so the scale would be the same as the plot above, your bode plot may not be exactly the same shape, depending on the scale used):
  • 66. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 66 As you can see the phase plot is exactly the same as before, and the magnitude plot is shifted up by 40dB (gain of 100). The phase margin is now about -60 degrees. This same result could be achieved if the y-axis of the magnitude plot was shifted down 40dB. Try this, look at the first Bode plot, find where the curve crosses the -40dB line, and read off the phase margin. It should be about -60 degrees, the same as the second Bode plot. We can find the gain and phase margins for a system directly, by using Matlab. Just enter the margin command. This command returns the gain and phase margins, the gain and phase cross over frequencies, and a graphical representation of these on the Bode plot. Let's check it out: margin(50,[1 9 30 40])
  • 67. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 67 Latihan : 7 Designing Lead and Lag Compensators Lead and lag compensators are used quite extensively in control. A lead compensator can increase the stability or speed of response of a system; a lag compensator can reduce (but not eliminate) the steady state error. Depending on the effect desired, one or more lead and lag compensators may be used in various combinations. Lead, lag, and lead/lag compensators are usually designed for a system in transfer function form. The conversions page explains how to convert a state-space model into transfer function form. Lead or phase-lead compensator using root locus A first-order lead compensator can be designed using the root locus. A lead compensator in root locus form is given by where the magnitude of zo is less than the magnitude of po. A phase-lead compensator tends to shift the root locus toward the left half plane. This results in an improvement in the system's stability and an increase in the response speed. How is this accomplished? If you recall finding the asymptotes of the root locus that lead to the zeros at infinity, the equation to determine the intersection of the asymptotes along the real axis is: When a lead compensator is added to a system, the value of this intersection will be a larger negative number than it was before. The net number of zeros and poles will be the same (one zero and one pole are added), but the added pole is a larger negative number than the added zero. Thus, the result of a lead compensator is that the asymptotes' intersection is moved further into the left half plane, and the entire root locus will be shifted to the left. This can increase the region of stability as well as the response speed. In Matlab a phase lead compensator in root locus form is implemented by using the transfer function in the form
  • 68. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 68 numlead=kc*[1 z]; denlead=[1 p]; and using the conv() function to implement it with the numerator and denominator of the plant newnum=conv(num,numlead); newden=conv(den,denlead);
  • 69. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 69 Lead or phase-lead compensator using frequency response A first-order phase-lead compensator can be designed using the frequency response. A lead compensator in frequency response form is given by Note that this is equivalent to the root locus form with p = 1/T, z = 1/aT, and Kc = a. In frequency response design, the phase-lead compensator adds positive phase to the system over the frequency range 1/aT to 1/T. A bode plot of a phase-lead compensator looks like the following The two corner frequencies are at 1/aT and 1/T; note the positive phase that is added to the system between these two frequencies. Depending on the value of a, the maximum added phase can be up to 90 degrees; if you need more than 90 degrees of phase, two lead compensators can be used. The maximum amount of phase is added at the center frequency, which is located at The equation which determines the maximum phase is
  • 70. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 70 Additional positive phase increases the phase margin and thus increases the stability of the system. This type of compensator is designed by determining a from the amount of phase needed to satisfy the phase margin requirements, and determining T to place the added phase at the new gain-crossover frequency. Another effect of the lead compensator can be seen in the magnitude plot. The lead compensator increases the gain of the system at high frequencies (the amount of this gain is equal to a). This can increase the crossover frequency, which will help to decrease the rise time and settling time of the system. In Matlab, a phase lead compensator in frequency response form is implemented by using the transfer function in the form numlead=[aT 1]; denlead=[T 1]; and using the conv() function to multiply it by the numerator and denominator of the plant newnum=conv(num,numlead); newden=conv(den,denlead); Lag or Phase-Lag Compensator using Root Locus A first-order lag compensator can be designed using the root locus. A lag compensator in root locus form is given by where the magnitude of zo is greater than the magnitude of po. A phase-lag compensator tends to shift the root locus to the right, which is undesirable. For this reason, the pole and zero of a lag compensator must be placed close together (usually near the origin) so they do not appreciably change the transient response or stability characteristics of the system. How does the lag controller shift the root locus to the right? If you recall finding the asymptotes of the root locus that lead to the zeros at infinity, the equation to determine the intersection of the asymptotes along the real axis is:
  • 71. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 71 When a lag compensator is added to a system, the value of this intersection will be a smaller negative number than it was before. The net number of zeros and poles will be the same (one zero and one pole are added), but the added pole is a smaller negative number than the added zero. Thus, the result of a lag compensator is that the asymptotes' intersection is moved closer to the right half plane, and the entire root locus will be shifted to the right. It was previously stated that that lag controller should only minimally change the transient response because of its negative effect. If the phase-lag compensator is not supposed to change the transient response noticeably, what is it good for? The answer is that a phase-lag compensator can improve the system's steady-state response. It works in the following manner. At high frequencies, the lag controller will have unity gain. At low frequencies, the gain will be z0/p0 which is greater than 1. This factor z0/p0 will multiply the position, velocity, or acceleration constant (Kp, Kv, or Ka), and the steady-state error will thus decrease by the factor z0/p0. In Matlab, a phase lead compensator in root locus form is implemented by using the transfer function in the form numlag=[1 z]; denlag=[1 p]; and using the conv() function to implement it with the numerator and denominator of the plant newnum=conv(num,numlag); newden=conv(den,denlag); Lag or Phase-Lag Compensator using Frequency Response A first-order phase-lag compensator can be designed using the frequency response. A lag compensator in frequency response form is given by
  • 72. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 72 The phase-lag compensator looks similar to a phase-lead compensator, except that a is now less than 1. The main difference is that the lag compensator adds negative phase to the system over the specified frequency range, while a lead compensator adds positive phase over the specified frequency. A bode plot of a phase-lag compensator looks like the following The two corner frequencies are at 1/T and 1/aT. The main effect of the lag compensator is shown in the magnitude plot. The lag compensator adds gain at low frequencies; the magnitude of this gain is equal to a. The effect of this gain is to cause the steady-state error of the closed-loop system to be decreased by a factor of a. Because the gain of the lag compensator is unity at middle and high frequencies, the transient response and stability are not impacted too much. The side effect of the lag compensator is the negative phase that is added to the system between the two corner frequencies. Depending on the value a, up to -90 degrees of phase can be added. Care must be taken that the phase margin of the system with lag compensation is still satisfactory. In Matlab, a phase-lag compensator in frequency response form is implemented by using the transfer function in the form numlead=[a*T 1]; denlead=a*[T 1];
  • 73. Materi Pendukung Kuliah : Sistim Pengaturan (Perhitungan, Pemrograman dan Visualisasi dengan MATLAB) 73 and using the conv() function to implement it with the numerator and denominator of the plant newnum=conv(num,numlead); newden=conv(den,denlead); Lead-lag Compensator using either Root Locus or Frequency Response A lead-lag compensator combines the effects of a lead compensator with those of a lag compensator. The result is a system with improved transient response, stability and steady-state error. To implement a lead-lag compensator, first design the lead compensator to achieve the desired transient response and stability, and then add on a lag compensator to improve the steady-state response.