12.MATLAB Tutorial
12.MATLAB Tutorial
To start creating a script, run the program and choose “New” from upper toolbox and
select “Script”. Now, you can start to create your script.
Working
directory Editor
panel
Command
window
Workspace
Working directory is the address of the folder which you work on it.
Editor panel is used to create and edit scripts, functions, etc.
Workspace contains your variables, matrices, etc. You can access the value assigned
variables from here.
Command window is used to call scripts, functions, variables etc. Moreover, you can
assign values to variables by using this window. You can also print or scan variable
values from here.
2 MATLAB BASICS
x =
3.4000
>> y=1E6
y =
1000000
>> z='hello'
z =
hello
A =
1 2 3
B =
1
2
3
3x3 matrix
>> C=[1,2,3 ; 4,5,6 ; 7,8,9]
C =
1 2 3
4 5 6
7 8 9
A =
0 0 0 0 0
Page 2 of 29
2.2 Arithmetic Operators
>> var1=10
var1 =
10
>> var2=5
var2 =
Addition:
>> var3 = var1 + var2
var3 =
15
Subtraction:
>> var3 = var1 - var2
var3 =
Multiplication:
>> var3 = var1 * var2
var3 =
50
Division:
>> var3 = var1 / var2
var3 =
Power:
>> var3 = var1^2
var3 =
100
3.1623
Page 3 of 29
2.3 Relational Operators
Example:
>> x=2;
>> y=3;
>> x>y
ans =
0
Note: 0 means that is False
>> x<y
ans =
1
Note: 1 means that is True
>> x==y
ans =
>> x~=y
ans =
Page 4 of 29
2.4 Logical Operators
Example:
Find the logical AND of two matrices. The result contains logical 1 (true) only where
both matrices contain nonzero values.
>> A = [5 7 0; 0 2 9; 5 0 0]
A = 3×3
5 7 0
0 2 9
5 0 0
>> B = [6 6 0; 1 3 5; -1 0 0]
B = 3×3
6 6 0
1 3 5
-1 0 0
>> A & B
ans = 3x3 logical array
1 1 0
0 1 1
1 0 0
Page 5 of 29
Example:
Find the logical OR of two matrices. The result contains logical 1 (true) where either
matrix contains a nonzero value. The zeros in the result indicate spots where both arrays have
a value of zero.
>> A = [5 7 0; 0 2 9; 5 0 0]
A = 3×3
5 7 0
0 2 9
5 0 0
>> B = [6 6 0; 1 3 5; -1 0 0]
B = 3×3
6 6 0
1 3 5
-1 0 0
>> A | B
ans = 3x3 logical array
1 1 0
1 1 1
1 0 0
Page 6 of 29
Example:
As a simple example, you can add two vectors with the same size.
>> A = [1 1 1]
A =
1 1 1
>> B = [1 2 3]
B =
1 2 3
>> A+B
ans =
2 3 4
Example:
You can compute the element-wise product of a scalar and a matrix.
>> A = [1 2 3; 1 2 3]
A =
1 2 3
1 2 3
>> 3.*A
ans =
3 6 9
3 6 9
Example:
You can calculate the product of two matrices.
>> A = [1 3;2 4]
A =
1 3
2 4
>> B = [3 0;1 5]
B =
3 0
1 5
Page 7 of 29
>> A*B
ans =
6 15
10 20
The previous matrix product is not equal to the following element-wise product.
>> A.*B
ans =
3 0
2 20
Output:
A =
3 5 7 8
9 6 4 3
4 5 7 7
10 20 45 12
To access a particular element in an array, you can specify row and column subscripts,
such as
>> A(2,3)
Output:
ans =
4
If you have a column or row vector, you can access a particular element in vector by
using only one subscript. For example,
>> A= [3 5 7 8 9 6 4 3]
A =
3 5 7 8 9 6 4 3
>> A(1,5)
ans =
9
Page 8 of 29
OR
>> A(5)
ans =
Example:
Let’s create a row vector.
ans =
-84
>> max(A)
ans =
75
30 75 49 24 23
Page 9 of 29
Finding index of a value in array. For example, index of 75 is found as follows.
>> indexOfValue=find(A==75)
indexOfValue =
3
You can check it, output of A(3) is 75.
Use the relational less than operator, <, to determine which elements of A are less than
30. Store the result in B.
>> B = A < 30
B =
0 1 0 1 0 1 1 1
Although B contains information about which elements in A are less than 30, it doesn’t
tell you what their values are. Rather than comparing the two matrices element by element,
you can use B to index into A.
>> A(B)
ans =
2 4 6 7 8
You can check that a matrix contains a particular value by using ismember function.
This function returns an array containing logical 1 (true) where the particular value is found
in matrix. For example,
>> ismember(30,A)
ans =
1
The matrix A contains 30.
>> ismember(10,A)
ans =
0
The matrix A does not contain 10.
Page 10 of 29
Determine which elements of C are also in A.
>> A= [ 30 -55 75 -84 49 -46 24 23]
>> C=[10 20 30 24]
>> L=ismember(C,A)
ans =
0 0 1 1
>> C(L)
ans =
30 24
C(3)=30 and C(4)=24 are found in A.
Example 1:
>> x=5;
>> disp(x);
5
>>
Example 2:
>> A=[ 1 2 3];
>> disp(A);
1 2 3
>>
Example 3:
>> z='hello';
>> disp(z);
hello
>>
Page 11 of 29
2.8 Printing Value of a Variable
Example :
a=3;
b=2.525;
c=a+b;
fprintf('%f \n',c)
5.525000
>>
Page 12 of 29
2.10 Importing a Data File
MyTable = importdata('MyDataFile.txt');
Now, numerical values in table assigned a matrix named OnlyValues. You can display
this variable or you can open from Workspace panel.
disp(OnlyValues)
Then, the output of command is
Page 13 of 29
1.0e+03 *
If you want to assign header of the table to a variable, use “.textdata” command as
follows.
Header = MyTable.textdata;
Now, text in the table was assigned a variable named Header.You can display this
variable or you can open from Workspace panel.
disp(Header)
You can use “load” function, but be careful while using. If you use “load” function,
your data file must contain only numerical values, therefore you must delete header lines from
your data file.
Example:
The content of “MyDataFile.txt” file is shown below. As you can see below, there is no
header line. When you use load function, if you have header lines like in previous example,
you will receive an error message.
Page 14 of 29
0.01 0.6113 0.001000 206.131 206.132 0 2375.33 2375.33
5 0.8721 0.001000 147.117 147.118 20.97 2361.27 2382.24
10 1.2276 0.001000 106.376 106.377 41.99 2347.16 2389.15
15 1.705 0.001001 77.924 77.925 62.98 2333.06 2396.04
20 2.339 0.001002 57.7887 57.7897 83.94 2318.98 2402.91
25 3.169 0.001003 43.3583 43.3593 104.86 2304.90 2409.76
30 4.246 0.001004 32.8922 32.8932 125.77 2290.81 2416.58
35 5.628 0.001006 25.2148 25.2158 146.65 2276.71 2423.36
40 7.384 0.001008 19.5219 19.5229 167.53 2262.57 2430.11
45 9.593 0.001010 15.2571 15.2581 188.41 2248.40 2436.81
50 12.350 0.001012 12.0308 12.0318 209.30 2234.17 2443.47
Now data file is imported and assigned a variable named MyTable. You can display
this variable or you can open from Workspace panel.
disp(MyTable)
Page 15 of 29
After importing data file, you can create vectors for each column as follows. For
example,
First column of MyTable matrix is temperature. Then,
Temperature = MyTable(:,1)
------------------------------------------------------------------------
Note:
MyTable(:,1) means all elements of column 1 of “MyTable” matrix.
MyTable(2,:) means all elements of row 2 of ”MyTable” matrix.
------------------------------------------------------------------------
myfile = fopen('DataFile.txt','w');
This command open a text file named DataFile.txt in writing mode (‘w’).
fprintf(myfile,'%f %f %f \n',firstrow);
This command was used to write elements of vector firstrow to the second line of
DataFile.txt file.
Page 16 of 29
fprintf(myfile,'%f %f %f \n',secondrow);
This command was used to write elements of vector secondrow to the third line of
DataFile.txt file.
fclose(myfile)
This command was used to close the data file. Do NOT forget close the data file.
After running the code, it creates a file named DataFile.txt in working directory. The
content of file is
This is header of my data file
1.500000 2.000000 3.500000
4.100000 5.400000 6.700000
2.12 If Statement
if expression
statements
elseif expression
statements
else
statements
end
Example:
a=1;
b=5;
if a<b
fprintf('a is less than b \n')
end
a is less than b
a=10;
b=5;
if a<b
fprintf('a is less than b \n')
end
When the code above is executed, it prints nothing because condition is false.
Page 17 of 29
Example:
a=7;
b=5;
if a<b
fprintf('a is less than b \n')
else
fprintf('a is greater than b \n')
end
a is greater than b
Example:
a=5;
b=5;
if a<b
fprintf('a is less than b \n')
elseif a>b
fprintf('a is greater than b \n')
else
fprintf('a is equal to b \n')
end
a is equal to b
Example:
x = 10;
minVal = 2;
maxVal = 6;
--------------------------------------------------------------
Note: Remember && is logical AND.
--------------------------------------------------------------
When the code above is executed, the result will be:
Page 18 of 29
2.13 Loops
The while loop repeatedly executes statements while a specified condition is true.
The syntax of a while loop in MATLAB is as following:
while <expression>
<statements>
end
The while loop repeatedly executes a program statement(s) as long as the expression
remains true.
Example:
a=10
% while loop execution
while( a < 20 )
fprintf('value of a: %d\n', a);
a = a + 1;
end
--------------------------------------------------------------
Note: % sign is used to write comments in code. This section
will not be executed.
--------------------------------------------------------------
Page 19 of 29
When the code above is executed, the result will be:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Example:
% ln(x)=1
% finding x value satisfying equation above iteratively
% RHS : right-hand side of equation
% LHS : left-hand side of equation
RHS = 1;
% initial value of absolute error
absolute_error=1;
% initial value of x
x=0;
% increment size
dx=0.001;
% The while loop repeatedly executes
% until absolute_error becomes less than 1e-3
while absolute_error>1e-3
% adding dx for each iteration
x=x+dx;
% calculate LHS of equation
LHS = log(x) ;
% calculate absolute error
absolute_error=abs(RHS-LHS)
end
disp(x)
x=2.716000
Page 20 of 29
2.13.2 For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
The syntax of a for loop in MATLAB is as following:
Example:
for x = 1:1:10
fprintf('value of x: %d\n', x);
end
Page 21 of 29
Example:
0.9000
0.8000
0.7000
0.6000
0.5000
0.4000
0.3000
0.2000
0.1000
Example:
for a = [24,18,17,23,28]
disp(a)
end
18
17
23
28
Example:
% x is a vector
x=[1 2 3 4 5 6 7 8 9 10];
% length(x) is the number of elements in vector x
% Calculating y = x^2 + x +1 for different x values
for i=1:length(x)
% Calculating and storing y values
y(i)=x(i)^2 + x(i) + 1;
% printing
fprintf(' x=%d --> y=%f \n',x(i),y(i))
end
Page 22 of 29
When the code above is executed, the result will be:
Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed. The scope
defines where the variables can be valid in MATLAB, typically a scope within a loop body is
from the beginning of conditional code to the end of conditional code. It tells MATLAB what
to do when the conditional code fails in the loop. MATLAB supports both break statement
and continue statement.
Break Statement
The break statement terminates execution of for or while loops. Statements in the loop
that appear after the break statement are not executed.
Page 23 of 29
Example:
a = 10;
% while loop execution
while (a < 20)
fprintf('value of a: %d\n', a);
a = a+1;
if( a > 15)
% terminate the loop using break statement
break;
end
end
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Continue Statement
The continue statement is used for passing control to the next iteration of a for or while
loop.
The continue statement in MATLAB works somewhat like the break statement. Instead
of forcing termination, however, 'continue' forces the next iteration of the loop to take place,
skipping any code in between.
Page 24 of 29
Example:
a = 10;
%while loop execution
while a < 20
if a == 15
% skip the iteration
a = a + 1;
continue;
end
fprintf('value of a: %d\n', a);
a = a + 1;
end
Example:
Creating a function that calculates circular area.
% Circular area function
% R is input parameter
% area is output parameter
% Name of function : CircleArea
% R is radius of circle, unit: cm
function area = CircleArea(R)
area = pi*R^2;
fprintf('area of circle is : %f cm^2 \n',area)
end
Page 25 of 29
First, you must save this script by using the function’s name like “CircleArea.m”.
Afterwards, go to command window and call your function as follows
>> CircleArea(1);
--------------------------------------------------------------
Note: You can also call your function within other scripts.
--------------------------------------------------------------
Example 2:
Using multiple inputs and output parameters.
There is a function below which is used to calculate average and standard deviation of a
data set.
First, you must save this script by using the function’s name like “stat.m”.
Afterwards, go to “editor panel” and create a new script which use stat.m function
and call your function within this script as follows.
10
standard_deviation =
3.5355
Page 26 of 29
3 EXAMPLES FOR ASSIGNMENT-2
You are given a thermodynamic property table for water which includes undefined
values. By creating a computer code, fill in the missing parts.
240 1485.3
5713.4 1273.0
T = 240; % Celsius-degree
u = 1485.3; % kJ/kg
Page 27 of 29
Checking that is necessary making interpolation.
P=Pressure(i);
vf = specificVolume_f(i);
vg = specificVolume_g(i);
uf = internalEnergy_f(i);
ug = internalEnergy_g(i);
After this, you must check the phase of water. It can be superheated. If it is super-heated
you must import superheated water table to MATLAB. In this case it is saturated.
Now you can calculate x and v. Then, you can print all properties as follows.
x = (u-uf)/(ug-uf);
v = vf + x * (vg-vf);
P = 5713.4; % kPa
u = 1273.0 % kJ/kg
A=find(Pressure<P);
j=A(end);
j is index of previous pressure value than P = 5713.4 kPa
B=find(Pressure>P);
k=B(1);
Page 28 of 29
k is index of next pressure value than P = 5713.4 kPa
Then you can find previous and next pressure values as follows.
P1 = Pressure(j);
P2 = Pressure(k);
Moreover, you can find corresponding properties to these pressure values as follows.
T1=Temperature(j);
T2=Temperature(k);
vf1=specificVolume_f(j);
vf2=specificVolume_f(k);
...
Now, you can make interpolation to find corresponding property values to P = 5713.4
kPa. After finding corresponding property values to P = 5713.4 kPa, you must check the
phase of water. It can be superheated. If it is superheated you must import superheated water
table to MATLAB.
You must do it on your own after this…
https://www.mathworks.com/help/matlab/
Page 29 of 29