IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

29
President University MATLAB Tutorial A First Course for Electrical Engineers Author: A. Suhartomo, Ph.D Bayu G. Wundari, M.Sc

Transcript of IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

Page 1: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

President University

MATLAB TutorialA First Course for Electrical Engineers

Author:A. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

Page 2: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

Vision and Mission

VisionPlaying an active role in the development of science and

technology in the field of Electrical Engineering, so in 2020 tobecome the leading study program in the nation to improve the

quality of life globally

Mission1 Developing an education system in the field of Electrical Engi-

neering with strong scientific background and broad insight,covering the concentrations that become the hallmark

2 Producing high quality and professional graduates in their ownconcentrations, that includes control, communication, and powersystems

3 To create and to develop science and technology, through innova-tive research activities, to enrich the competency of the grad-uates in global market competition

4 To return positive contribution to the society and the surround-ings, through transfer of science and technology, whose bene-fit can be perceived directly by the society and the surround-ings.

PUPresident University

2016

Page 3: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB TutorialA First Course for

Electrical Engineer

Module 1

Introduction to Basic Operations in MATLAB

PUPresident University

Page 4: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

Contents

1 Objectives 4

2 Basic Operations in MATLAB 4

3 Simple Arithmetic Operations 5

4 Advanced Mathematical Operations in MATLAB 5

5 Matrix Operations in MATLAB 65.1 Matrix Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

6 Making Mathematical Equations with MATLAB 116.1 Solving A Polynomial Equation Numerically . . . . . . . . . . . . . . 116.2 Solving A Polynomial Equation Symbolically . . . . . . . . . . . . . . 11

7 Making Plots with MATLAB 12

8 Making Functions in MATLAB 14

9 Making Selection with MATLAB 15

10 Making Loops with MATLAB 17

11 Case Study: Making Gaussian Function 19

12 Exercises 22

Bibliography 28

3

Page 5: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

Introduction to Basic Operations in MATLAB

A. Suhartomo, Ph.DBayu G. Wundari, M.Sc

Date Performed:Partners:

Instructor:

1 Objectives

1 To understand some fundamental matrix operations in MATLAB

2 To learn how to solve polynomial equations with MATLAB

3 To learn how to create plots with MATLAB

4 To implement some basic algorithms such as looping, making selection and mod-ular programming in MATLAB

2 Basic Operations in MATLAB

MATLAB (MATrix LABoratory) has been one of the most powerful software thatis used in many disciplines such as science, engineering, economic, and so on. In thefield of science and engineering, undoubtedly, MATLAB has been a very convenienttool to perform data analysis. There has been numerous papers in which scientistsuse MATLAB to turn data into knowledge. Even in the world of biology, nowadays,it is difficult for scientists to have a good data analysis without using MATLAB.Therefore, learning MATLAB will be crucial, particularly for scientists and engi-neers. It might be difficult in some certain cases, but the results are rewarding andimportant throughout this course. The contents of this material, anyway, are mainlytaken from [1], [2], and [3]. So, let’s get started.

4

Page 6: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

A very basic use of MATLAB is that it can be used as a calculator. Though thiskind of calculator has bigger size (depending on the size of our laptop or PC) thana pocket calculator, but its function is remarkably superior than any pocket calcu-lator. MATLAB provides the user a way to perform a more complex and completecomputation. The computation can range from simple arithmetic operations suchas addition and subtraction, to complex mathematical equations such as differentialequations.

3 Simple Arithmetic Operations

The arithmetic operations that are considered as simple include addition, subtrac-tion, multiplication, and division. These operations are straightforward and aredepicted in Table 1:

Table 1: Simple Arithmetic Operations in MATLAB

No Operation Math Expression MATLAB Expression1 Addition 2+3 >>2+32 Subtraction 7-5 >>7-53 Multiplication 3*5 >>3*54 Division 8:2 >>8/2

5 Mixed7+9:3 >>7+9/3(9+7):3 >>(9+7)/3

4 Advanced Mathematical Operations in MAT-

LAB

Mathematical operations that are considered as ”advanced” include: powers, log,exponentials, and trigonometry. Their implementation in MATLAB are given inTable 2.

5

Page 7: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

Table 2: Advanced Mathematical Operations in MATLAB

No Operation Math Expression MATLAB Expression1 Power 23 >>2ˆ32 Natural Logarithm ln(2.7183) >>log(2.7813)3 Arbitrary Base Logarithm 7Log(35) >>Log(35)/log(7)4 Exponential e3 >>exp(3)

5 Trigonometric (in radian)sin(pi/4) >>sin(pi/4)cos(pi/4) >>cos(pi/4)tan(pi/4) >>tan(pi/4)

5 Matrix Operations in MATLAB

As implied by its name, MATLAB provides a very convenient way when dealing withmatrices. Therefore, whenever we use MATLAB, we need to always think about thedata in matrix form. MATLAB defines a matrix in the same way as we define it inmathematics, a collection of vectors. In this regard, a vector is a matrix with singlerow or single column. And actually, the operations in MATLAB are matrix-based.Even when MATLAB perform an operation on a single number or a scalar, it impliesthat the number is a matrix with dimension (1,1).

Vectors and matrices as designated by square brackets [ ] in which everything insidethe brackets is part of the vector or matrix. An (m,n) matrix in MATLAB meansthat the matrix has m rows and n columns. Hence, the matrix with dimension(m,1) is called a column vector while (1,n) is called a row vector. Table 3 gives someexamples of how to construct matrix in MATLAB:

6

Page 8: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

Table 3: Matrix Operations in MATLAB

No Operation Matrix Expression MATLAB Expression1 Scalar [a] >>a2 Row Vector

(a b c

)>>[a b c]

3 Column Vector

abc

>>[a;b;c]

4 Matrix

(a b cd e f

)>>[a b c; d e f]

5 Transpose (a b c)T >>[a b c]’6 Addition (a b c) + (d e f) >>[a b c] + [d e f]7 Subtraction (a b c) - (d e f) >>[a b c] - [d e f]

8 Multiplication (a b c) X

abc

[a b c] * [d e f]’

9 Element-wise Multiplication (a b c).X (d e f) >>[a b c].* [d e f]10 Element-wise Division (a b c)./ (d e f) >>[a b c]./ [d e f]

Where the Roman letters are either real or imaginary numbers. To extract a par-ticular element of matrix (row i column j) , we just need to write down the matrixalong with the index of element (i, j).

Example:� M = [5 2 4 ;4 -1 3]M = 5 2 4

4 -1 3� M(1,2)ans =2

Remember that because MATLAB is matrix-based, the matrix operations for addi-tion and subtraction are element-wise, meaning that the operations are performed onthe elements that have the same index in each matrices. However, for multiplication,the operation is performed according to the rule given in the matrix multiplication.Matrix multiplication can also be done element-wisely by adding a dot (.), but thematrices must have the same dimension. Matrix division can only be done element-wisely. Examples of element-wise multiplication and division are shown in Table 3.Please consult MATLAB documentation for further insight.

7

Page 9: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

5.1 Matrix Indexing

Matrix indexing sounds like a topic that can be understood intuitively and easily.Therefore, it is often being underestimated. But, matrix indexing, believe or not,is often confusing in some particular cases such as in image processing becausewe often need to capture only certain elements in the matrix into computation.Thus, knowing how to index a matrix and take the corresponding elements is highlydemanding as it will boost the efficiency of our program.

For brevity, consider a 4x5 matrix that is comprised of a series of number from 1 to20. Hence, the matrix would look like this:

M =

1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 20

We can access an element of the matrix M above by giving the index of its row andcolumn separated by a comma. The coordinate of the very first element of matrixM is denoted by (1,1). Hence, to access the element at the first row and the firstcolumn, we specify it as M(1,1):� M(1,1)

ans =

1

To access multiple elements of the matrix, we can use a subarray operation byspecifying a vector of integers for each index. It will be much easier to explain thesubarray operations through some examples.

Suppose that we want to access the elements in the second row of matrix M. We canaccess those elements by specifying the column coordinate with a colon operator (:).So the command would look like:� M(2,:)

ans =

6 7 8 9 10

8

Page 10: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

The colon operator used in the column coordinate denotes that we want the wholeelements If we want to access the elements in the third column:� M(:,3)ans =381318

We can also access multiple rows:� M([3,1],2)ans=122

And as can be seen from this example above, the rows do not have to be in order.Here, we requested the order to be row 3, followed by row 1. The same holds forcolumns.

For accessing multiple rows and multiple columns, we can specify them as:� M([3,1,2],[3,1,4,2])ans=13 11 14 123 1 4 28 6 9 7

Another trick to fetching data from a matrix in MATLAB is to use the commandend. The keyword end is used for specifying the last row or column in a subarrayoperation. For example:� M(1,3:end)ans=3 4 5

The command end can also be used for direct specification too:� M(end,end)ans=20

Sometimes, we also want to assign a certain value or to change an element of thematrix that we have created. To do this, we just only need to specify the coordinate

9

Page 11: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

of the element(s) that we want to change and assign them with the new value(s).For example:� M(3,3) = 99ans=1 2 3 4 56 7 8 9 1011 12 99 14 1516 17 18 19 20

As can be seen from this example that the element of M(3,3) has changed from 13to 99.

MATLAB provides two built-in functions to create a matrix that is commonly usedfor memory allocation. Those two commands are zeros and ones. zeros is used forcreating an (m,n) matrix whose whole elements are zero. ones is used for creatingan (m,n) matrix whose whole elements are one. Observe the following examples:� zeros(2,3)ans=0 0 00 0 0

� ones(2,3)ans=1 1 11 1 1

We can also implement a bit of arithmetic operations to assign an arbitrary numberto the matrix. Suppose that we have a (3,4) zero matrix A and we want to assign avalue of one to the elements whose both indices are even. So for element (2,2) willbe one, while element (1,1) will be still zero. Here is a script as an example run:� A = zeros(5,6);� A(2:2:end,2:2:end)ans =0 0 0 0 0 00 1 0 1 0 10 0 0 0 0 00 1 0 1 0 10 0 0 0 0 0

10

Page 12: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

6 Making Mathematical Equations with MATLAB

In MATLAB, we can solve polynomial in two ways: numerically and symbolically.Either approach is acceptable with the only difference lies in the expression of thepolynomial and the MATLAB command to solve the polynomial (finding the rootsof the polynomial).

6.1 Solving A Polynomial Equation Numerically

Suppose that we want to write a polynomial A defined as follows:

A = x2 + 3x+ 2

And we want to find the roots of this polynomial. The MATLAB command chainsrequired to do this are as follows:� A= [1 3 2]

A= 1 3 2

� roots(A)ans =-2-1

Notice that we only need to define the coefficients of the polynomial in matrix formand type in the command ‘roots’ to get the roots of the polynomial.

6.2 Solving A Polynomial Equation Symbolically

Although MATLAB solves polynomial equations primarily with the numerical math,it can also use symbolic math to solve the equations. Symbolic math assigns avariable to be written in the expression of the function in the MATLAB commandwindow or editor. We need a special command to do this and it is called ’syms’.

Suppose that we have a polynomial A as we defined before and we want to find theroots of it with the symbolic method. The MATLAB command chains to do this isgiven below:

� syms x� A = x2 + 3x+ 2A = x2 + 3x+ 2

11

Page 13: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

� solve(A)ans =-2-1

Notice that we use ‘solve’ instead of ‘roots’ to find the roots of the polynomial.

7 Making Plots with MATLAB

Every data that we get from our research needs to be visualized so that people canunderstand our results easily. No one will have any passion to read our results ifwe only present the raw data, in the sense that the results only show the numbersthat we get directly from our measurement tools. However, we and those who areinterested in our research can interpret our results better when we visualize our datain the form of graphs or plots. To this end, MATLAB provides a convenient andfast way to make plots of our data.

MATLAB treats data in a discrete manner, therefore, the main idea of plotting datawith MATLAB is to give MATLAB two vectors, let say vector x containing data inx-axis, and vector y containing data in y-axis. Then MATLAB will map one-to-oneeach data in vector x to vector y. And since the data mapping is one-to-one, thenobviously MATLAB requires the two vectors to have the same length. In doing allthese procedures, we use the plot(x,y) command, where x denotes a vector of dataalong the x-axis and y denotes a vector of data along the y-axis. And once again,we should remember that the two vectors x and y must be in the same length.

In most cases, we often have several data set that we want to plot in differentgraph, but we want to present them side by side. To this end, MATLAB providesthe command subplot by which we can put our plots in a matrix that we can seeout plots next to each other. To illustrate how to create plots using the commandplot and subplot, it is easier to explain the process through the following example.Suppose we have a waveform defined in Equation 7.1 in the 0 ≤ t ≤ 5 secondsinterval.

f(t) = 3e−4t cos(5t)− 2e−3t sin(2t) +t2

t+ 1(7.1)

Instead of treating the equation as one entity, we will break it into four sub-equationsso that we can employ the subplotcommand and learn how to use it in MATLAB.The MATLAB script for making plots in this example is as follows:

12

Page 14: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

t = 0:0.01:5; % define t-axis in 0.01 incrementsy1 = 3 ∗ exp(−4 ∗ t). ∗ cos(5 ∗ t);y2 = −2 ∗ exp(−3 ∗ t). ∗ sin(2 ∗ t);y3 = t.ˆ2./(t+ 1);y4 = y1 + y2 + y3;

subplot(2,2,1) % we want to have a 2x2 matrix and%we want to put our first plot in the coordinate (1,1)plot(t,y1)xlabel(’t’) % give a label to the x-axisylabel(’y1’) % give a label to the y-axistitle(′y1 = 3 ∗ exp(−4 ∗ t). ∗ cos(5 ∗ t)′) % give a title to the plot

subplot(2,2,2) % we want to put our second plot in the coordinate (1,2)plot(t,y2)xlabel(’t’)ylabel(’y2’)title(′y2 = −2 ∗ exp(−3 ∗ t). ∗ sin(2 ∗ t)′)

subplot(2,2,3) % we want to put our second plot in the coordinate (2,1)plot(t,y3)xlabel(’t’)ylabel(’y3’)title(′y3 = t.ˆ2./(t+ 1)′)

subplot(2,2,4) % we want to put our second plot in the coordinate (2,2)% and to put all plots in the same graphplot(t,y1)hold on % use this command to put plots in the same graphplot(t,y2)plot(t,y3)plot(t,y4)hold off % don’t forget to turn in offxlabel(’t’)ylabel(’y’)legend(’y1’,’y2’,’y3’,’y4’) % give a legendtitle(’y4 = y1 + y2 + y3’)

13

Page 15: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

The resulted plot is shown in Figure 7.1

Figure 7.1: The resulted plot for the wave function f(t) = 3e−4t cos(5t) −2e−3t sin(2t) + t2

t+1

8 Making Functions in MATLAB

MATLAB also provides users to code systematically. To code in a systematic waymeans that the programmer creates a block of codes for a particular purpose. Forexample, the programmer can create a function add(x,y) for adding two real num-bers x and y, but not for performing multiplication. Coding in this way helps theprogrammer in many ways, especially during debugging the codes.

Suppose we want to create a function add(x,y) for adding two real numbers. Thefunction takes two input arguments called x and y and returns one output argumentcalled z. The first thing that we need to do is to open a new MATLAB editor andtype in function to tell MATLAB that we want to create a function. The script tocreate this function is as follows:

function z = fxAdd(x,y)% Function to add two real numbers% Input arguments:% x,y : real number% Output argument(s):

14

Page 16: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

% z : real number

z = x + y;

Having created the function, then we save the file and name it as ’fxAdd.m’. Makesure to name the file with the same name as the name of the function so that MAT-LAB can find the location of the file that we created properly. And also rememberthat we need to save the file in the working directory. One more important remarkin creating a function is to make a proper notes in the function we made, such asthe purpose of the function, the way the function works, the type of the input andthe output, etc.

After saving the file, then we can try to run our function by typing fxAdd(3,5) inthe MATLAB command window. If everything was done properly, then we will getthe answer 8.

A peace of advice in making function in MATLAB, it will be very helpful if we nameour function with the same name as the saved filename. Though MATLAB still runthe function that has different saved filename, but having the same name will putus at ease when trying to remember the name of the function that we’ve created.

9 Making Selection with MATLAB

Selection occurs when we have more than one choices to choose. And in facing thosechoices, we are forced to make a decision by collecting some conditions to choose thebest option that would give the best result. That said, after conducting a sequenceof instructions, we arrive at some point where we do a test. As depicted in Figure9.1, if the test is true (represented in the Boolean value), we do one thing (TrueBlock), and if false, we do a different thing (False Block). Having made a branching(either the code chose True Block or False Block), then we can optionally go to thenext instruction.

15

Page 17: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

Figure 9.1: Branching program

To perform selection in MATLAB, we use if...else statements. The following exam-ple illustrates the usage of the statement in MATLAB. Suppose we are given a taskto create a function called letterGrade that takes a positive integer called score asits input argument and return a letter grade according to the following scale: A: 91and above; B: 81-90; C: 71-80; D: 61-70; F: below 61. The MATLAB script for thisfunction is as follows:

function grade = letterGrade(score)% Function to grade a score% Input argument:% score: integer% Output argument:% grade: char

if score < 61grade = ’F’;

elseif score ≥ 61 && score ≤ 70grade = ’D’;

elseif score ≥ 71 && score ≤ 80

16

Page 18: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

grade = ’C’;elseif score ≥ 81 && score ≤ 90

grade = ’B’;elseif score ≥ 91

grade = ’A’;end

Then we save the file in the working directory. When we run the function by typingin letterGrade(45) in the command window, then if everything was done properly,we will get F as the answer.

10 Making Loops with MATLAB

Looping is another very common problem in programming tasks that refers to thesituation where we need to do some repetition on a certain task. Depending on thecomplexity of the program, sometimes we need to involve a block of code more thanonce, ten, or even 1000. Therefore, the concept of looping is necessary to make ourcodes better.

The idea of iteration is quite straightforward. Start with a Test in Figure 10.1, thecode evaluates the Test. If it evaluates to True, the program executes the loop bodyonce and go back to re-evaluate the Test. The program repeats the same processuntil it evaluates the Test to False. Once it evaluates to False, the code will executethe next sequence of code.

17

Page 19: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

Figure 10.1: Iteration program

MATLAB provides two commands to execute iteration program: the commandfor...end and while...end. Consider the following example to see how to use thesecommands in MATLAB. Suppose we want to add the value of x to itself for y times.We will make this code using for...end command and while...end command to seethe difference.

x = 3;y = 10;

%% repetition using for loopfor i=1:y

x = x + x;end

display(x)

%% repetition using while loopx = 3;while y =0

x = x + x;

18

Page 20: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

y = y - 1;end

display(x)

If everything was done properly, both methods will give 3072 as the answer.

11 Case Study: Making Gaussian Function

Now, let’s try to translate what we’ve learnt so far into a case in which we’re goingto create a 1D Gaussian function and to plot it. Though MATLAB has a built-in function to make the Gaussian, but we will try to create our own Gaussianfunction. The Gaussian is one of the most important function that appears in manymathematical modelling. Many natural phenomena can be approximated by suchfunction.

To jog our memory about the Gaussian function, recall that it is expressed as:

G(x) =1

σ√

2πe−

(x−µ)2

2σ2 (11.1)

where σ denotes the standard deviation and µ represents the mean value.

To this end, we will create two functions: one for the Gaussian function itself thatwe name it as fxGauss (fxGauss.m), and the other one for plotting it that we nameit as fxGaussPlot (fxGaussPlot.m). The MATLAB script for these functions areas follows:

function y = fxGauss(mu,sigma,x)%%% Function to create a Gaussian function%% Input arguments:% mu: mean value% sigma = standard deviation% x = x axis%%% Output argument:% y: a vector containing the value of the Gaussian

19

Page 21: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

%%y = (1/(sigma*sqrt(2*pi)))*exp(-((x-mu).ˆ2)/(2*sigmaˆ2));

Once we’re done, we need to save this script into our working directory and nameit as fxGauss.m. The next is to write fxGaussPlot:

function fxGaussPlot(x,y,mu,sigma)%%% Function to plot a Gaussian function% % Input arguments:% mu: mean value% sigma = standard deviation% x = x axis% y = a vector containing the value of the Gaussian

%%titleText = strcat(’Gaussian Function, mu = ’, num2str(mu), ...’, sigma = ’, num2str(sigma));plot(x,y,’LineWidth’,3)title(titleText, ’FontSize’,14)xlabel(’x’,’FontSize’,14)ylabel(’y’,’FontSize’,14)ylim([0 6])set(gca,’fontsize’,14)

Again, we have to save the fxGaussPlot into our working directory and name it asfxGaussPlot.m.

Having done that, we will write another script that implement those two functions.We will create four kinds of Gaussian that have different mean and standard devi-ation so that we can see how they look like. The MATLAB script are as follows(chp1 gauss.m):

xGauss = -5:0.1:5;

for i=0:3mu = i-2;sigma = 0.5+i*0.25;

20

Page 22: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

yGauss = fxGauss(mu,sigma,xSigma);

% plot the functionsubplot(2,2,i+1)fxGaussPlot(xGauss,yGauss,mu,sigma)

end

And the result is shown in Figure 11.1. There are three important characteristics ofthe Gaussian that we can observe in Figure 11.1. First, the mean value correspondsto the location of the center of the Gaussian (the peak value). Second, the standarddeviation corresponds to the width of the function. The greater the standard de-viation, the wider the function. Lastly, the area under the curve must remain thesame, therefore, as the Gaussian gets wider, its height will get decreased.

Figure 11.1: Gaussian functions with different mean and standard deviation

Notice in this example that we used a for-loop to create the four Gaussians. Theuse of functions that we’ve created enabled us to write a neat and clean code. Thefunction fxGauss prevents us from rewriting the same code to create other Gaussianthat has different mean and standard deviation. The use of fxGaussPlot functionalso prevents us from rewriting the same command to plot those four Gaussians.

21

Page 23: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

12 Exercises

1. Construct the following matrix in MATLAB

A =

1 52 36 4

Add a semicolon (;) at the end of the command before pressing ENTER. Whatis the difference? What is the function of the semicolon?

2. Construct another matrix B as follows

B =

1 11 10 1

Try to perform an addition on matrix A with B (A+B) and matrix A with thetranspose of B (A+BT ). Could you explain how is the matrix addition donein MATLAB and why didn’t one of the operations work?

3. Construct another matrix C as follows

C =[2 2 2

]Try to perform a multiplication on matrix A with C (A*C) and matrix Cwith A (C*A). Could you explain how is the matrix multiplication done inMATLAB and why didn’t one of the operations work?

4. Construct another matrix D as follows

D =

1 01 20 0

Perform the element-wise multiplication A.*D and D.*A and explain the dif-ference of this operation with the ones done in step 4.

5. Find the roots of the following polynomial equations using both numeric andsymbolic methods.

(a) y = x2 + 5x+ 4

(b) y = x3 + 5x2 + 2x+ 1

22

Page 24: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

(c) y = x2 + 4

(d) y = x4 + 5x2 + 2x

6. Make a plot for the following functions:

(a) A sequence of rectangular pulses with a period of 2 seconds, amplitude 1unit, duty cycle 50%, and the pulses run for 10 seconds. Hint: you cantry to use the built-in function called rectangularPulse.

(b) A sinusoidal signal with frequency 2 Hz, amplitude 1 unit, and it runs for10 seconds.

(c) A Gabor function which is defined as:

f(x) = e−−(x−µ)2

2σ2 cos(ω0(x− µ) + φ) (12.1)

7. Half-wave rectification. The notion of half-wave rectification refers to acomputational technique that eliminates negative values of a function. Oneway to do this is by introducing a nonlinearity to the function such as squar-ing or taking only positive values. See Figure 12.1 as an example in which thesquare wave is rectified by only taking the positive values. Write a functioncalled fxHalfWaveRect that takes a vector and a binary number as its in-put arguments. The function outputs another vector that has been half-waverectified using the method specified by the binary number. A binary number1 will tell the function that the method of rectification is squaring the input,while a zero will represent taking only the positive values. In addition, thefunction should also plot the original wave and the rectified version side byside as shown in Figure 12.1

23

Page 25: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

Figure 12.1: Half-wave rectification

8. Write a MATLAB script to create a plot like shown in Figure 12.2.

Figure 12.2: Sinusoidal and rectangular waves

9. Write a simple function called fxPlotSin to plot a sinusoidal wave. Thefunction only takes f as its input argument representing the frequency of the

24

Page 26: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

wave. The plot should cover four times its period. In addition, please give theplot some labels on its axis and give the plot a title.

10. Write a function called fxPlotMixSin to plot three sinusoidal waves withsubplot command. The function takes f1 and f2 as its input argument repre-senting the frequency of the first and the second wave respectively. The firstplot should be the sinusoidal wave with frequency f1, the second plot is for f2and the third plot is for the sum of the two waves. Please give the plot somelabels on its axis and give the plot a title.

11. Write a function called fxOddIndices that takes two positive integers m andn as input arguments. This function returns one matrix as an output argu-ment. The whole elements of the matrix are zeros, except for the ones forwhich both indices are odd need to be ones. For example:� fxOddIndices(5,6)ans =1 0 1 0 1 00 0 0 0 0 01 0 1 0 1 00 0 0 0 0 01 0 1 0 1 0

12. Write a function called fxAlternate that takes two positive integers m and nas input arguments and outputs an (m,n) matrix whose elements must followthe following rule: the elements whose indices for which its sum is even, theirvalue is one; other elements are zero. For example:� fxAlternate(4,5)ans =1 0 1 0 10 1 0 1 01 0 1 0 10 1 0 1 0

13. Write a function called fxPeriSum that takes a matrix A as its input argumentand outputs the sum of the matrix elements that are on ”perimeter” of theinput matrix A. In other words, it adds together the elements that are in thefirst and the last rows and columns.

14. Write a function called fxWeight that computes the weight of a thing withmass m under a gravity g. The function takes m and g as its input arguments.The input m denotes the mass of the thing in kg and g denotes the value of

25

Page 27: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

the gravity acceleration in m/s.

15. Write a function that computes the area and circumference of a circle. Thefunction only takes a scalar input r and returns an output called area that isthe area of the circle and a second output called cf that is the circumferenceof the same circle.

16. Make a branching function for the following problems:

(a) A function that takes integer as an input from the user. If the inputinteger is odd, then print ’Odd’, if it is even, then print out ’Even’. Hint:use the command input to get data from the user and the commanddisplay to print out an argument or a string.

(b) A function that computes the bus fare one must pay in a given city basedon the distance traveled. Here is how the fare is calculated: the first kmis Rp. 7500,-. Each additional km up to a total trip distance of 10 kmis Rp. 1500,-. Each additional km over 10 km is Rp. 2000,-. Km’s arerounded to the nearest integer other than the first km which must be paidin full once the journey begins. Children 18 or younger and seniors 60 orolder get a 20% discount. The inputs to the function are the distance ofthe journey and the age of the passenger. Return the fare in Rupiah.

(c) A function that sort a 3-element vector either in decreasing or increasingorder. The function takes two inputs: the first input is the 3-element vec-tor, and the second one is a binary number in which a binary 1 representincreasing order and 0 denotes decreasing order. The function returnsanother 3-element vector that has been in order.

17. Convert the following into code that uses a while loop.

print 2print 4print 6print 8print 10print Goodbye!

18. Convert the following into code that uses a for loop.

print Hello!print 10print 8print 6

26

Page 28: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

print 4print 2

19. Write a loop program that computes a factorial of a given number. So, forexample, if we define a number to be 6, your code should print out the result:21, which is 1 + 2 + 3 + 4 + 5 + 6.

20. Make a MATLAB function that creates a sequence of numbers. The functiontakes integer x and y as inputs in which x denotes the first number of thesequence and y denotes the final number of the sequence. Write the functionfor the following sequences:

(a) An even number sequence. Let’s call the function even and if we calleven(1,7), then it will generate an output: 2,4,6. If we call even(2,6),it will give an output 2,4,6.

(b) An odd number sequence. Let’s call the function odd and if we callodd(1,7), then it will generate an output: 1,3,5,7. If we call odd(2,6),it will give an output 3,5.

(c) A Fibonacci number sequence. Let’s call the function fib and if we callfib(1,7), then it will generate an output: 1,1,2,3,5,7. If we call fib(2,6),it will give an output 2,3,5,7.

21. Consider the definition: function [s1, s2, sums] = sines(pts,amp,n1,n2). Theinput, pts, is an integer, but amp, n1, and n2 and are not necessarily integers.Output argument s1 is a row vector whose length (number of elements) equalspts. The elements of s1 are the values of the sine function when it is givenequally spaced arguments that start at zero and extend through n1 periods ofthe sine. In other words, n1 is the frequency of s1 in Hz. The amplitude of thesine wave equals amp. The vector s2 is the same as s1 except that s2 containsn2 as its frequency. The vector sums is the sum of s1 and s2. Also make plotsfor those three signals by using subplot command with dimension (3,1)!

27

Page 29: IksanBukhori · 2019. 1. 17. · Created Date: 11/18/2016 9:43:59 AM

MATLAB Tutorial

A First Course for Electrical EngineersA. Suhartomo, Ph.D

Bayu G. Wundari, M.Sc

Bibliography

[1] J. Michael Fitzpatrick and Akos Ledeczi. Computer Programming with MAT-LAB. Fitzle, 2013.

[2] Steven T. Karris. Circuit Analysis I with MATLAB - Computing and Simulink- SimPowerSystems - Modeling. Orchard Publications, 2009.

[3] Steven T. Karris. Circuit Analysis II with MATLAB Applications. OrchardPublications, 2003.

28