Beruflich Dokumente
Kultur Dokumente
2019-11-09
1
Notes
3. You are recommended to run the programs within the module in your computer, to know
the output of the program.
4. It is more preferable to try the programs listed in this module to grasp deeper on what the
program does.
5. You are highly advised to learn programming from other sources or materials and explore
further about the programming language you use.
2
Contents
1 Module 1 4
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4.1 Arithmetic Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4.2 Operator Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4.3 Relational Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4.4 Logical Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5 Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2 Module 2 8
2.1 Looping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.1.1 While Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.1.2 For Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2 Nested looping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3 Module 3 10
3.1 Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.1.1 Array Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.1.2 Array and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4 Module 4 12
4.1 Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4.2 Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4.3 Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
5 Module 5 15
5.1 Data Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.1.1 Creating Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.1.2 Reading and Writing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.1.3 Data Accessing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.1.4 Extracting Extreme Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
5.1.5 Data Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
5.1.6 Frequency Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
5.1.7 Determining Range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.1.8 Simple Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.1.9 Correlation Coefficient . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
5.1.10 Data Unstacking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
5.2 Data Visualization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.2.1 Bar Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.2.2 Histogram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
5.2.3 Pie Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
5.2.4 Stacked Bar Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
5.2.5 Line Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
5.2.6 Area Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
5.2.7 Scatter and Bubble Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3
1 Module 1
1.1 Introduction
In this module, we are using Matlab that is compatible with version 9.1 or later. Matlab IDE is
paid, therefore you are recommended to learn Octave (a programming language, compatible and
free alternative to Matlab). You can try Octave Online on https://octave-online.net/
• Matlab is case-sensitive, which means small letters and capital letters have different inter-
pretation.
• Matlab does not detect indent and line changes. However, it is highly advised to properly
align indent as it is handy for debugging and code readability.
• Variables in Matlab are implicit and dynamics. In other words, a variable does not need to
be defined by the data type. Yet in this module, we still have to learn the existing data type.
In Matlab, the following program writes out "Hello, World!" to the screen:
% This is a comment
%{
Apart from that , everything between percentage sign followed by open curly
bracket and percentage followed by closed curly bracket are ignored too. Make
sure there are no texts in the same lines as the percent and curly bracket .
%}
The part marked as 1 writes out ’Hello, World!’ to the screen. The syntax ’\n’ will move line
after writing them. In other words, the output of the program above is ’Hello, World!’ followed
by ’This is my next program’ in the next like.
1
Apart from that, note that each statement ends with a semicolon (;).
To make an input, we need something to store the data inputted. For example, the following
program receives input numbers and rewrite the numbers entered.
prog/matlab-operators-and-special-characters.html
4
fprintf (’You input a text %s and a number %d\n’, S, N + 5); % 4
On number (1) and (3), program reads input from the user and entered to the variable S and N.
Noticed that to read a string string (a set of character), use ’s’ as a second parameter for input.
Apart from int, string, Matlab gets to receive float (real number) data, and etc.
There are several types of data, but in this course we will only use these data types often:
Contoh penggunaan:
B = true; % Boolean
I = 12345; % Integer
R = 2.331973; % Real number
S = ’def ’; % Text
1.4 Operator
5
1.4.3 Relational Operator
1.5 Control
We can control the flow of our program in programming. Thus, our program behaves depends
on users’ input. Suppose, we make a program that checks if a number is positive:
if (N > 0)
fprintf (’%d is a positive number ’, N)
end
...
if (N > 0)
fprintf (’%d is a positive number ’, N)
else % N <= 0
fprintf (’%d is not a positive number ’, N)
end
...
...
if (N > 0)
fprintf (’%d is a positive number ’, N)
elseif (N < 0)
fprintf (’%d is a negative numbe ’, N)
else % N == 0
fprintf (’%d is zero ’, N)
end
...
Notice that we can repeat the else operation. Apart from that, we can place if inside of if.
6
...
if (N >= 0)
if (N > 0)
fprintf (’%d is a positive number ’, N)
else % N == 0
fprintf (’%d is zero ’, N)
endif
else % N < 0
fprintf (’%d is a negative number ’, N)
end
...
7
2 Module 2
2.1 Looping
In programming, repetitive processing is required often to achieve a certain result. If this repetition
is done manually, the source file size would be too large. A simple example that writes ”Hello
World” on the screen 1000 times would require at least 1000 command lines. By using repetition
syntax, this problem can be solved using only a program of a few lines.
for i = 1:1000
fprintf (" Hello world\n");
end
One of the looping syntax that is frequently used is While-Do syntax. The program checks if a
condition given is fulfilled before running the statement in it.
The following is a program that receives a and b, and then writes out a, a + 1, a + 2, . . . , b − 1, b.
a = input(’’);
b = input(’’);
i = a;
while i <= b
fprintf (’%d\n’, i);
i = i + 1;
end
The other form of looping syntax is for. This syntax is usually used for repetition parameters are
known. For loops can also be made with a while-do loop.
The following is a program that receives a and b, and then writes out a, a + 1, a + 2, . . . , b − 1, b.
a = input(’’);
b = input(’’);
for i = a:b
fprintf (’%d\n’, i)
end
The range can have two or three parameters. For more details, consider the following code part:
2 : 5 % 2, 3, 4, 5
7 : -1 : 2 % 7, 6, 5, 4, 3, 2
3 : 0.5 : 5 % 3, 3.5, 4, 4.5, 5
8
2.2 Nested looping
Furthermore, looping can be assigned inside of looping, known as nested looping. For example,
a program that forms square patterns.
n = input(’’);
for i = 1:n
for j = 1:n
fprintf (’*’);
end
end
9
3 Module 3
3.1 Array
Array is a variable of a single name, but contain multiple values. Each element in an array can be
accessed through index.
Index 1 2 3 4 5 6 7 8 9 10
A 10 5 7 11 19 23 35 37 12 1
• A(10)= 1
• A(1) = 10
• A(7) = 35
In the example above, we have a variable named A, contains 10 values, where each value can be
accessed through index. To access the xth index, use A(x). We can assume the value A(x) as a
stand-alone variable. This concept is what we call an array. Note that indexing in Matlab starts at
1, differs from the other programming languages, that use zero-based indexing.
Example of declaration:
In Matlab, the array used is essentially a matrix with a size of one by the length defined. The
array A defined in the example above, are A(1), A(2), . . . , A(10). For a cell array, it can be accessed
using a curly bracket A{1}. Accessing the index value beyond the limit bound will cause the array
to stretch to satisfy the index that is replacing.
Just assume them as a variable so that every operation types on variables also apply to arrays. For
example, the following array:
10
Therefore the following table array are defined for index #1 up to #10. Then we can make an
operation of an element.
Table(2)= input(’’);
If we were given 5 elements, and we need to save the element on the table, with:
However, the input method above is laborious, especially for a large array. It would be more
efficient if we input using looping.
11
4 Module 4
4.1 Function
What is a function? A function is part of a program that can work on certain tasks or operations
outside the main program. The function returns value according to the algorithms given in the
function.
The function above is named as square and returns the squared value of x. The output variable
must be written before the function name, followed by an equal symbol. The output variable
returns when the function is invoked on the main program.
Example: A complete program that receives input and outputs, the input number squared.
From the example above, the variable in the main program is n. Whereas in function, the variable
is named as x. Even though x changes, the values of n in the main program will not change.
A function can receive more than one input parameter. In addition to that, functions can do specific
tasks like a normal program does, but still unable to change variables in the main program.
Note: You are not recommended to use array(s) as function parameters, as these are not taught in
Introduction to Computation Course.
4.2 Procedure
Procedures are similar to functions, but with no return value, despite the syntax named as function.
For example, a program that writes out menus:
12
fprintf (’1. Burger \n’);
fprintf (’2. Friend Chicken \n’);
fprintf (’3. Instant Noodle \n’);
food_option = input(’Masukkan pilihan : ’);
Like in the program above, writing menus multiple times can be summarized to:
4.3 Matrix
Matrix is essentially 2 dimensional array, it can be declared with the following syntax:
From the code above, a matrix named A is declared with element type integer and initial value of
0, with a size of 10 rows × 20 columns. Similar to array, the i-th row and j-th column are accessed
with A(i,j) syntax.
Example: A program that reads each element in a matrix and rewrite each element to the console.
n = input(’’);
m = input(’’);
A = zeros(n, m);
for i = 1:n
for j = 1:m
13
fprintf (’masukkan elemen baris %d kolom %d: ’, i, j);
A(i,j) = input(’’);
end
end
for i = 1:n
for j = 1:m
fprintf (’%d ’, A(i,j));
end
fprintf (’\n’);
end
The following is an example of a program that reads matrix A with a size of n × m, matrix B with
a size of n × l.
n = input(’’);
m = input(’’);
l = input(’’);
A = zeros(n, m);
B = zeros(m, l);
C = zeros(n, l);
for i = 1:n
for j = 1:m
fprintf (’masukkan elemen B baris %d kolom %d’, i, j);
A(i, j) = input(’’);
end
end
for i = 1:m
for j = 1:l
fprintf (’masukkan elemen B baris %d kolom %d’, i, j);
B(i, j) = input(’’);
end
end
for i = 1:n
for j = 1:l
C(i, j) = 0;
for k = 1:m
C(i, j) = C(i, j) + A(i, k)*B(k, j);
end
fprintf (’%d ’, C(i, j));
end
fprintf (’\n’);
end
14
5 Module 5
Make sure that the name and age have the same quantity to make a table!
To read a data from .csv / excel workbook, we use readtable. To write the data to .csv or excel
workbook, for example:
Note: You are highly recommended to work on the same folder rather than using the format
D:/path/ke/file.xlsx.
15
M(5 ,:)
% Tahun Cakupan Tingkat_Inflasi
% 2009 ’Prov. Jawa Barat ’ 2.02
16
% 2009 ’Kota Bandung ’ 2.11
% 2009 ’Prov. Jawa Barat ’ 2.02
% 2009 ’Nasional ’ 2.78
% 2011 ’Kota Bandung ’ 2.75
We get to make a frequency table, based on the data on a selected column, meaning that it list of
the possible values in that column in a unique form, then count the tally of the ’unique’ data.
We are tabulating the frequency for the year 2008 to 2013. In Matlab, tabulation of integers or
floats displays value from 1 to 2007 too, which contains no tallies. This can be negated by adding
categorical to it.
17
% list of frequency tally of years (tahun) (kolom 1) on a data
tabulate ( categorical (M.Tahun))
% Value Count Percent
% 2008 3 16.67%
% 2009 3 16.67%
% 2010 3 16.67%
% 2011 3 16.67%
% 2012 3 16.67%
% 2013 3 16.67%
The table made above are for displaying purpose only, it cannot be process. Therefore, by adding
a variable name, it will return as a cell array, can hardly be used for visualizing, what we want to
do is convert the data to an actual table.
For cross-tabulation of frequency distribution between two distinct data variables, contingency
table, refer the stacked bar graph section.
summary (M)
18
inflasi_avg = mean(M. Tingkat_Inflasi ) % 5.8189
Two selected columns may have correlation. These are measured with correlation coefficient, and
are interpreted as follows:
The following are example of a correlation between year and inflation level:
Unstacking the stacked data to split the data by their unique entries. For instance, splitting the
variable cakupan (area scopes) into these separate variables.
From the result above, there are 3 area scopes, which can be separated for each of them. The
output in unstacked format is:
19
Each row in the table above contains data from rows in the inflation data that have the same value
in the grouping variable, year. The order of the unique values in year determines the order of the
data in the table above.
However, the data for each group combination of year and region scope only have one data. For
a case of a combination of multiple data:
The unstacked data and the aggregation function mean applied to multiple rows in the same group
that have the same values in the indicator variable. The only combination of data with more than
one data is the males from California (CA), with a total number of pets of 7 from three entries,
giving a mean of 2.3333.
The default aggregation function is sum, omitting the aggregation function parameter results:
20
5.2 Data Visualization
Loading up data:
21
The bar graph can have multiple data represented by different colors. In this instance, we are
comparing the number of children Tdata.num_children and number of pets Tdata.num_pets in a
single bar graph.
Horizontal bar graph syntax are very similar to that of the conventional bar graph, but instead of
’xticklabel’, it uses ’yticklabel’ for labeling.
figure (3)
barh( Tdata.age);
set(gca ,’yticklabel ’,Tdata.name); grid on
xlabel (’Age (years)’); ylabel (’Name ’);
title (’Age of a person , but horizontal bar ’)
22
5.2.2 Histogram
% Histogram of a person age based on the group: 0 to 100 with a step of 20.
figure (4)
histogram (Tdata.age ,0:20:100) ; grid on
xlabel (’Age ’); ylabel (’Frequency ’)
title (’Individual person age grouped from 0 to 100 with a step of 20’)
23
Where, the parameters in this syntax are (data_column, ranges)
24
5.2.4 Stacked Bar Chart
Very similar to the grouped bar graph but stacked. In this instance, we are tabulating frequency
table between two distinct column in a data, which are gender (first order) and state (second
order).
From the result above, the variable state is unstacked into three, which are California (CA), the
DC, and Texas (TX). Aggregation function sum is applied, resulting a contingency table.
In the following code, in the bar graph syntax, curly bracket is used instead of normal bracket.
This ’convert’ table into double, to be plotted.
25
% Number of children ( num_children ) dan pets ( num_pets ) in a
% single stacked bar chart
figure (7)
bar ([ Tdata. num_children ,Tdata. num_pets ],’stacked ’)
set(gca ,’xticklabel ’,Tdata.name); grid on
xlabel (’Name ’); ylabel (’Age (years)’);
title (’Number of children and pets per person ’)
legend ({’children ’,’pets ’},’Location ’,’bestoutside ’)
26
% Population change of bears , dolphins , and whales
% from year to year in a single line chart
figure (9)
plot( Tanimal .Year , [ Tanimal .Bears Tanimal . Dolphins Tanimal . Whales ]);
grid on; xlabel (’Year ’); ylabel (’Population ’)
legend ({’Bears ’,’Dolphins ’,’Whales ’},’Location ’,’bestoutside ’)
title (’Population change of three selected animals each year in line chart ’)
27
5.2.6 Area Chart
The area graph has a very similar concept to the line graph. The data stacks with more than one
different data. In default, area graph interval always starts from zero, unlike the line graph, which
depends on the extreme values.
28
% Population change of bears , dolphins , and whales
% from year to year in a single area chart
figure (11)
area( Tanimal .Year , [ Tanimal .Bears Tanimal . Dolphins Tanimal . Whales ]);
grid on; xlabel (’Year ’); ylabel (’Population ’)
legend ({’Bears ’,’Dolphins ’,’Whales ’},’Location ’,’bestoutside ’)
title (’Population change of three selected animals through the years ’)
29
5.2.7 Scatter and Bubble Plot
30
Where, the parameters scatter plot are (xaxis, yaxis, [], COLOR, ’*’).
Similar to scatter graph, the bubble graph has a third parameter represented by the size of the
bubble. More values, bigger bubble.
% Number of total medal for Top 10 countries correlated with gold medal
% possession at x-axis and silver medal at y-axis on bubble plot
figure (13)
Tmedali10 = Tmedali (1:10 ,:) % extract the first 10 data
scatter ( Tmedali10 .gold , Tmedali10 .silver , [ Tmedali10 .total],’filled ’, ’green ’)
grid on; xlabel (’gold medal ’); ylabel (’silver medal ’)
title (’Correlation between Total , Gold , and Silver medal possessions of the Top
10 ’)
Where, the bubble plot parameters are (xaxis, yaxis, [bubble size], COLOR, ’filled’)
31