MATLAB Tutorial of Fundamental Programming
-
Upload
sprynter19 -
Category
Documents
-
view
229 -
download
0
Transcript of MATLAB Tutorial of Fundamental Programming
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
1/34
MMAATTLLAABBTTuuttoorriiaall ooff
FFuunnddaammeennttaall PPrrooggrraammmmiinngg
Prepared by:
Khairul Anuar IshakDepartment of Electrical, Electronic & System Engineering
Faculty of Engineering
Universiti Kebangsaan Malaysia
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
2/34
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
3/34
MATLAB tutorial of fundamental programming
ii
Contents
1 Introduction to MATLAB 1
What is MATLAB? 1
MATLAB System 2
The Advantages of MATLAB 2
Disadvantages of MATLAB 3
2 Getting Started 4
Starting MATLAB 4
Ending a Session 8
3 MATLAB Basics 9
Variables and Arrays 9
Arithmetic Operations 14
Common MATLAB Functions 16
4 Plotting and Visualization 17
Plotting in MATLAB 17
Images in MATLAB 24
5 Programming 25
Data Types 25
M-File Programming 27
Flow Control 30
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
4/34
CHAPTER 1: Introduction to MATLAB
1
What is MATLAB?
CHAPTER 1
Introduction to MATLAB
What is MATLAB?
MATLAB (short for MATrix LABoratory) is a special-purpose computer program optimized
to perform engineering and scientific calculations. It is a high-performance language for
technical computing. It integrates computation, visualization, and programming in an easy-to-use
environment where problems and solutions are expressed in familiar mathematical notation.
Typical uses include:
Math and computation Algorithm development Modelling, simulation and prototyping Data analysis, exploration and visualization Scientific and engineering graphics Application development, including Graphical User Interface (GUI) building
MATLAB is an interactive system whose basic data element is an array that does not require
dimensioning. This allows you to solve many technical computing problems, especially those
with matrix and vector formulations, in a fraction of the time it would take to write a program in
a scalar non-interactive language such as C, C++ or Fortran.
MATLAB has evolved over a period of years with input from many users. In university
environments, it is the standard instructional tool for introductory and advanced courses in
mathematics, engineering and science. In industry, MATLAB is the tool of choice for high-
productivity research, development and analysis.
MATLAB features a family of application-specific solution called Toolboxes. Very
important to most users of MATLAB, toolboxes allow you to learn and apply specializedtechnology. Toolboxes are comprehensive collections of MATLAB function (m-files) that
extend the MATLAB environment to solve particular classes of problems. Areas in which
toolboxes are available include signal processing, control systems, neural networks, fuzzy logic,
wavelets, image processing, simulation and many others.
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
5/34
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
6/34
CHAPTER 1: Introduction to MATLAB
3
Disadvantages of MATLAB
there are many special-purpose toolboxes available to help solve complex problems in
specific areas. There is also an extensive collection of free user-contributed MATLAB
programs that are shared through the MATLAB Web site.
4. Device-Independent Plotting. Unlike most other computer languages, MATLAB hasmany integral plotting and imaging commands. The plots and images can be displayed on
any graphical output device supported by the computer on which MATLAB is running.
5. Graphical User Interface. MATLAB includes tools that allow a programmer tointeractively construct a graphical user interface, (GUI) for his or her program. With this
capability, the programmer can design sophisticated data-analysis programs that can be
operated by relatively inexperienced users.
6. MATLAB Compiler. MATLABs flexibility and platform independence is achieved bycompiling MATLAB programs into a device-independent p-code, and then interpreting
the p-code instructions at runtime. Unfortunately, the resulting programs can sometimes
execute slowly because the MATLAB code is interpreted rather than compiled.
Disadvantages of MATLAB
MATLAB has two principal disadvantages. The first is that it is an interpreted language and
therefore can execute more slowly than compiled languages. This problem can be mitigated by
properly structuring the MATLAB program, and by the use of the MATLAB compiler to
compile the final MATLAB program before distribution and general use.
The second disadvantage is cost: a full copy of MATLAB is five to ten times more expensive
than a conventional C or Fortran compiler. This relatively high cost is more than offset by then
reduced time required for an engineer or scientist to create a working program, so MATLAB is
cost-effective for businesses. However, it is too expensive for most individuals to consider
purchasing. Fortunately, there is also an inexpensive Student Edition of MATLAB, which is a
great tool for students wishing to learn the language. The Student Edition of MATLAB is
essentially identical to the full edition.
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
7/34
CHAPTER 2: Getting Started
4
Starting MATLAB
CHAPTER 2
Getting Started
Starting MATLAB
You can start MATLAB by double-clicking on the MATLAB icon or invoking the
application from the Start menu of Windows. The main MATLAB window, called the
MATLAB Desktop, will then pop-up and it will look like this:
Figure 2.1: The Default MATLAB desktop
When MATLAB executes, it can display several types of windows that accept commands or
display information. It integrates many tools for managing files, variables and applications within
the MATLAB environment. The major tools within or accessible from the MATLAB desktop
are:
1. The Current Directory Browser2. The Workspace Window3. The Command Window4. The Command History Window5. The Start Button6. The Help Window
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
8/34
CHAPTER 2: Getting Started
5
Starting MATLAB
If desired, this arrangement can be modified by selecting an alternate choice from [View]
[Desktop Layout]. By default, most MATLAB tools are docked to the desktop, so that they
appear inside the desktop window. However, you can choose to undock any or all tools,
making them appear in windows separate from the desktop.
The Command Window
Figure 2.2: The Command Window
The Command Window is where the command line prompt for interactive commands is
located. Once started, you will notice that inside the MATLAB command window is the text:
To get started, select MATLAB Help from the Help menu.
>>
Click in the command window to make it active. When a window becomes active, its titlebardarkens. The >> is called the Command Prompt, and there will be a blinking cursor right after
it waiting for you to type something. You can enter interactive commands at the command
prompt (>>) and they will be executed on the spot.
As an example, lets enter a simple MATLAB command, which is the date command. Click
the mouse where the blinking cursor is and then type date and press the ENTERkey. MATLAB
should then return something like this:
>> date
ans =
01-Sep-2006
Where the current date should be returned to you instead of 01-Sep-2006. Congratulation!
You have just successfully executed your first MATLAB command!
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
9/34
CHAPTER 2: Getting Started
6
Starting MATLAB
The Command History Window
Figure 2.3: The Command History Window
The Command History Window, contains a log of commands that have been executed within
the command window. This is a convenient feature for tracking when developing or debugging
programs or to confirm that commands were executed in a particular sequence during a multi-
step calculation from the command line.
The Current Directory Browser
Figure 2.4: The Directory Browser
The Current Directory Browser displays a current directory with a listing of its contents.
There is navigation capability for resetting the current directory to any directory among those set
in the path. This window is useful for finding the location of particular files and scripts so that
they can be edited, moved, renamed or deleted. The default directory is the Work subdirectory of
the original MATLAB installation directory.
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
10/34
CHAPTER 2: Getting Started
7
Starting MATLAB
The Workspace Window
Figure 2.5: The Workspace Window
The Workspace Window provides an inventory of all the items in the workspace that are
currently defined, either by assignment or calculation in the Command Window or by importing
with a load or similar command from the MATLAB command line prompt. These items consist
of the set of arrays whose elements are variables or constants and which have been constructed or
loaded during the current MATLAB session and have remained stored in memory. Those which
have been cleared and no longer are in memory will not be included. The Workspace Window
shows the name of each variable, its value, its array size, its size in bytes, and the class. Values of
a variable or constant can be edited in an Array Editor which is launched by double clicking its
icon in the Workspace Window.
The Help Window
Figure 2.6: The Help Window
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
11/34
CHAPTER 2: Getting Started
8
You can access the online help in one of several ways. Typing help at the command prompt
will reveal a long list of topics on which help is available. Just to illustrate, try typing help
general. Now you see a long list of general purpose MATLAB commands. In addition, you
can also get help on the certain command. For example, date command. The output of help also
refers to other functions that are related. In this example the help also tells you, See also NOW,
CLOCK, DATENUM. You can now get help on these functions using the three different commands
as well.
Ending a Session
>> help date
DATE Current date as date string.
S = DATE returns a string containing the date in dd-mmm-yyyy format.
See also NOW, CLOCK, DATENUM.
There is a much more user-friendly way to access the online help, namely via the MATLAB
Help Browser. Separate from the main desktop layout is a Help desktop with its own layout. This
utility can be launched by selecting [Help][MATLAB Help] from the Help pull down menu.
This Help desktop has a right side which contains links to help with functions, help with
graphics, and tutorial type documentation.
The Start Button
The Start Button (see figure 2.1) allows a user to access MATLAB tools, desktop tools, help
files, etc. it works just like the Start button on a Windows desktop. To start a particular tool, just
click on the Start Button and select the tool from the appropriate sub-menu.
Interrupting Calculations
If MATLAB is hung up in a calculation, or is just taking too long to perform an operation,
you can usually abort it by typing [CTRL + C] (that is, hold down the key labeled CTRL, and press
C).
Ending a Session
One final note, when you are all done with your MATLAB session you need to exit
MATLAB. To exit MATLAB, simply type quit orexit at the prompt. You can also click on the
special symbol that closes your windows (usually an in the upper right-hand corner). Anotherway to exit is by selecting [File][Exit MATLAB]. Before you exit MATLAB, you should be
sure to save any variables, print any graphics or other files you need, and in general clean up
after yourself.
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
12/34
CHAPTER 3: MATLAB Basics
9
Variables and Arrays
CHAPTER 3
MATLAB Basics
Variables and Arrays
The fundamental unit of data in any MATLAB program is the array. An array is a collection
of data values organized into rows and columns and known by a single name. Individual data
values within an array are accessed by including the name of the array followed by subscripts in
parentheses that identify the row and column of the particular value. Even scalars are treated as
arrays by MATLAB they are simply arrays with only one row and one column. There are threefundamental concepts in MATLAB, and in linear algebra, are scalars, vectors and matrices.
1. A scalar is simply just a fancy word for a number (a single value).2. A vector is an ordered list of numbers (one-dimensional). In MATLAB they can be
represented as a row-vector or a column-vector.
3. A matrix is a rectangular array of numbers (multi-dimensional). In MATLAB, a two-dimensional matrix is defined by its number of rows and columns.
This is a scalar, containing 1 element
10=
a
[ ]4321=b
=
3
2
1
c
=
987
654321
d
This is a 14 array containing 4 elements, known as a row vector
This is a 31 array containing 3 elements, known as a column vector
This is a 33 matrix, containing 9 elements
In MATLAB matricies are defined inside a pair of square braces ([]). Punctuation marks of a
comma (,), and semicolon (;) are used as a row separator and column separator, respectfully.
You can also use a space as a row separator, and a carriage return (the ENTERkey) as a column
separator as well.
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
13/34
CHAPTER 3: MATLAB Basics
10
Variables and Arrays
Examples 3.1
Below are examples of how a scalar, vector and matrix can be created in MATLAB.
>>my_scalar = 3.1415
my_scalar =
3.1415
>>my_vector1 = [1, 5, 7]
my_vector1 =
1 5 7
>>my_vector2 = [1; 5; 7]
my_vector2 =
1
5
7
>>my_vector2 = [157]
my_vector2 =
1
5
7
>>my_matrix = [8 12 19; 7 3 2; 12 4 23; 8 1 1]
my_matrix =
8 12 197 3 2
12 4 238 1 1
>>my_vector1 = [1 5 7]
my_vector1 =
1 5 7
Indexing into an Array
Once a vector or a matrix is created you might needed to extract only a subset of the data, and
this is done through indexing.
Row 1
Row 2
Col 1 Col 2 Col 3
A 2-by-3
Matrix
Figure 3.1: An array is a collection of data values organized into rows and columns
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
14/34
CHAPTER 3: MATLAB Basics
11
Variables and Arrays
Individual elements in an array are addressed by the array name followed by the row and
column of the particular element. If the array is a row or column vector, then only one subscript
is required. For example, according to the example 3.1:
o my_vector2(2) is 5o my_matrix(3,2) is 4 ormy_matrix(7) is 4
The Colon Operator
The colon (:) is one of MATLABs most important operators. It occurs in several different
forms.
Examples 3.2
1. To create an incremental or a decrement vector>>my_inc_vec1 = [1:7]
my_inc_vec1 =
[ 1 2 3 4 5 6 7]
>>my_inc_vec2 = [1:2:7]
my_inc_vec2 =
[ 1 3 5 7]
>>my_dec_vec = [5:-2:1]
my_dec_vec =
[ 5 3 1]
2. To refer portions of a matrix/vector>>my_matrix = [8 12 19; 7 3 2; 12 4 23; 8 1 1]
my_matrix =
8 12 19
7 3 2
12 4 23
8 1 1
>> new_matrix1 = my_matrix(1:3,2:3)
new_matrix1 =
12 19
3 2
4 23
>> new_matrix2 = my_matrix(2:4,:)
new_matrix2 =
12 4 23
8 1 1
NOTES: If the colon is used by itself within subscript, it refers to all the elements in a row orcolumn of a matrix!
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
15/34
CHAPTER 3: MATLAB Basics
12
Variables and Arrays
Concatenating Matrices
Matrix concatenation is the process of joining one or more matrices to make a new matrix.
The expression C = [A B] horizontally concatenates matrices A and B. The expression C = [A;
B] vertically concatenates them.
Examples 3.3
Reshaping a Matrix
Here are a few examples to illustrate some of the ways you can reshape matrices.
Examples 3.4
Reshape 3-by-4 matrix A to have dimensions 2-by-6.
>> A = [8 19; 7 2];
>> B = [1 64; 4 5; 3 78];
>> C = [A; B]
C =
8 19
7 2
1 64
4 5
3 78
>>A = [1 4 7 10; 2 5 8 11; 3 6 9 12]
A =
1 4 7 10
2 5 8 11
3 6 9 12
>> B = reshape(A, 2, 6)
B =
1 3 5 7 9 112 4 6 8 10 12
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
16/34
CHAPTER 3: MATLAB Basics
13
Variables and Arrays
Examples 3.5
Transpose A so that the row elements become columns or vice versa. You can use either the
transpose function or the transpose operator (). To do this:
>> A = [1 4 7 10; 2 5 8 11; 3 6 9 12];
>> B = A
B =
1 2 3
4 5 6
7 8 910 11 12
General Function for Matrix and Vector
There are many MATLAB features which cannot be included in these introductory notes.
Listed below are some of the MATLAB functions regard to matrix and vector.
Basic Vector Function
MATLAB includes a number of built-in functions that you can use to determine a number of
characteristics of a vector. The following are the most commonly used such functions.
size Returns the dimensions of a matrixlength Returns the number of elements in a matrixmin Returns the minimum value contained in a matrixmax Returns the maximum value contained in a matrixsum Returns the sum of the elements in a matrixsort Returns the sorted elements in a matrixabs Returns the absolute value of the elements in a matrix
Examples 3.6
The following example demonstrates the use some of these functions.
>>mnA = min(A)
mnA =
1
>>mxA = max(A)
mxA =
4
>> sumA = sum(A)
sumA =
10
>> stA = sort(A)
stA =
1 2 3 4
>> A = [3 1 2 4];>> szA = size(A)
szA =
1 4>> lenA = length(A)
lenA =
4
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
17/34
CHAPTER 3: MATLAB Basics
14
Arithmetic Operations
Functions to Create a Matrix
This following section summarizes the principal functions used in creating and handling
matrices. Most of these functions work on multi-dimensional arrays as well.
diag Create a diagonal matrix from a vectorcat Concatenate matrices along the specified dimensionones Create a matrix of all oneszeros Create a matrix of all zerosrand Create a matrix of uniformly distributed random numbersrepmat Create a new matrix by replicating or tiling another
Examples 3.7
The following example demonstrates the use some of these functions.
Arithmetic Operations
MATLAB can be used to evaluate simple and complex mathematical expressions. When we
move from scalars to vectors (and matrices), some confusion arises when performing arithmetic
operations because we can perform some operations either on an element-by-element (array
operation) or matrices as whole entities (matrix operation). Expressions use familiar
arithmetic operators:
Array Operators
Operation MATLAB Form Comments
Addition A + B Array addition is identical
Subtraction A - B Array subtraction is identical
Multiplication A .* B Element-by-element multiplication ofA and B. Both
arrays must be the same shape, or one of them must
be a scalar
Division A ./ B Element-by-element division ofA and B. Both arrays
must be the same shape, or one of them must be a
scalar
>> C = rand(4,3)
C =
0.9501 0.8913 0.8214
0.2311 0.7621 0.4447
0.6068 0.4565 0.6154
0.4860 0.0185 0.7919
>>A = zeros(2,4)
A =
0 0 0 00 0 0 0
>> B = 7*ones(1,3)
B =
7 7 7
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
18/34
CHAPTER 3: MATLAB Basics
15
Arithmetic Operations
Power A .^ B Element-by-element exponentiation ofA and B. Both
arrays must be the same shape, or one of them must
be a scalar
Examples 3.8
The following example demonstrates the use some of these operations.
Matrix Operators
Operation MATLAB Form Comments
Addition A + B Array addition is identical
Subtraction A - B Array subtraction is identical
Multiplication A * B Matrix multiplication of A and B. The number of
columns in A must equal the number of rows in B.
DivisionA / B
Matrix division defined by A * inv(B), whereinv(B) is the inverse of matrix B.
Power A ^ B Matrix exponentiation of A and B. The power is
computed by repeated squaring
Examples 3.9
>> A = [1 4 7 10; 2 5 8 11; 3 6 9 12]
A =
1 4 7 10
2 5 8 11
3 6 9 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
>> C = A.*B
C =
1 8 21 40
10 30 56 88
27 60 99 144
>> A = [1 2 3 4];
>> B = A.^2
B =
1 4 9 16
>> A = [ 2 4 ; 8 10]
A =
2 4
8 10
>> B = [2 4; 2 5]
B =
2 4
2 5
>> C = A./B
C =
1 14 2
>> A = [ 2 4 ; 8 10];
>> B = [2 4; 2 5];
>> C = A*B
C =
12 2836 82
>> A = [ 2 4 ; 8 10];
>> B = [2 4; 2 5];
>> C = B*A
C =
36 4844 58
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
19/34
CHAPTER 3: MATLAB Basics
16
Common MATLAB Functions
Built-in Variables
MATLAB uses a small number of names for built-in variables. An example is the ans
variable, which is automatically created whenever a mathematical expression is not assigned to
another variable. Table below lists the built-in variables and their meanings. Although you canreassign the values of these built-in variables, it is not a good idea to do so, because they are used
by the built-in functions.
Variable Meaningans Value of an expression when that expression is not assigned to a variableeps Floating-point precisioni,j
Unit imaginary number, i = j = 1 pi , 3.14159265
realmax Largest positive floating-point numberrealmin Smallest positive floating-point numberInf
, a number larger than realmax, the result of evaluating0
1
NaN
Not a number, (e.g., the result of evaluating0
0
Examples 3.10
>> x = 0;
>> 5/x
Warning: Divide by zero
ans =Inf
>> x = 0;
>> x/x
Warning: Divide by zero
ans =
NaN
Common MATLAB Functions
A few of the most common and useful MATLAB functions are shown in table below. These
functions will be used in many times. It really helps you when one needs to manage variables and
workspace and to perform an elementary mathematical operation.
Managing Variables and Workspace
who List current variableswhos List current variables, long formclear Clear variables and functions from memorydisp Display matrix or textclc Clear command windowdemo Run demonstrations
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
20/34
CHAPTER 3: MATLAB Basics
17
Examples 3.11
Built-in Function of Elementary Math
abs(x) Calculates x
angle(x) Returns the phase angle of the complex value x, in radiansexp(x) Calculates xemod(x)
Remainder or modulo functionlog(x) Calculates the natural logarithm xelog
sqrt(x) Calculates the square root ofxsin(x) Calculates the sin(x), with x in radianscos(x) Calculates the cos(x), with x in radianstan(x) Calculates the tan(x), with x in radiansceil(x) Rounds x to the nearest integer towards positive infinityfix(x) Rounds x to the nearest integer towards zerofloor(x) Rounds x to the nearest integer towards minus infinityround(x) Rounds x to the nearest integer
Examples 3.12
>> whos
Name Size Bytes Class
ans 1x1 226 sym object
y 1x1 8 char array
v 4x5 200 double arrayx 1x3 500 double array
>> z = 2*sin(pi/2)+log(2)
z =
2.6931
>> z = round(z)
z =
3
Common MATLAB Functions
>> z = 2*sin(pi/2)+log(2)
z =
2.6931
>> z = round(z)
z =
3
>> str = [MATLAB Baguss..!];>> disp(str);
MATLAB Baguss..!
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
21/34
CHAPTER 4: Plotting and Visualization
18
Plotting in MATLAB
CHAPTER 4
Plotting and Visualization
Plotting in MATLAB
MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as
annotating and printing these graphs. This section describes a few of the most important graphics
functions and provides examples of some typical applications.
Creating a Plot
The plot function has different forms, depending on the input arguments. If y is a vector,
plot(y) produces a piecewise linear graph of the elements ofy versus the index of the elements
ofy. If you specify two vectors as arguments, plot(x,y) produces a graph ofy versus x.
For example, to plot the value of the sine function from zero to 2, use:
Creating Line Plots
Examples 4.1
>> x = 0:pi/100:2*pi;
>> y = sin(x);
>>plot(x,y);
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
22/34
CHAPTER 4: Plotting and Visualization
19
Plotting in MATLAB
This is the basic command of plotting a graph. Besides that, MATLAB has commands which
will let you add titles and labels and others in order to make your figures more readable.
However, you need to keep the figure window open while executing these commands.
>> xlabel(Radian);
>> ylabel(Amplitude);
>> title(Plot of sin(x) vs x);
>> grid on;
The current limits of this plot can be determined from the basic axis function. So, in order to
modify the x-axis within [0 2], you need to run this function:
>> axis([0 2*pi -1 1]);
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
23/34
CHAPTER 4: Plotting and Visualization
20
Plotting in MATLAB
Annotating Plots
You can adjust the axis tick-mark locations and the labels appearing at each tick mark. For
example, this plot of the sine function relabels the x-axis with more meaningful values.
Example 4.2
>> x = 0:pi/100:2*pi;
>> y = sin(x);
>> plot(x,y);
>> set(gca,XTick,-pi:pi/2:pi);
>> set(gca,XTickLabel,{-pi,-pi/2,0,pi/2,pi});
>> xlabel('-\pi \leq \Theta \leq \pi');
>> ylabel('sin(\Theta)');>> title('Plot of sin(\Theta)');
Creating a Semilogarithmic Plot
Semilogarithmic plot is another type of figuring a graph by rescaling if the new data falls
outside the range of the previous axis limits.
Example 4.3
>> x = linspace(0,3);
>> y = 10*exp(-2*x);
>> semilogy(x,y);>> grid on;
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
24/34
CHAPTER 4: Plotting and Visualization
21
Plotting in MATLAB
Specifying the Color and Size of Lines
You can control a number of line style characteristics by specifying values for line properties.
LineWidth Width of the line in units of pointsMarkerEdgeColor Color of the marker or the edge color for filled markersMarkerFaceColor Color of the face of filled markersMarkerSize Size of the marker in units of points
Example 4.4
>> x = -pi:pi/10:pi;
>> y = tan(sin(x)) - sin(tan(x));
>> plot(x,y,'--rs','LineWidth',2,...
'MarkerEdgeColor','k',...'MarkerFaceColor','g','MarkerSize',10);
Multiple Plots
Often, it is desirable to place more than one plot in a single figure window. This is achieved
by three ways:
The subplot Function
The subplot Function breaks the figure window into an m-by-n matrix of small subplots and
selects the ith subplot for the current plot. The plots are numbered along the top row of the figure
window, then the second row, and so forth.
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
25/34
CHAPTER 4: Plotting and Visualization
22
Plotting in MATLAB
Example 4.5
>> x = linspace(0,2*pi);
>> subplot(2,2,1);
>> plot(x,sin(x));>>
>> subplot(2,2,2)
>> plot(x,sin(2*x));
>>
>> subplot(2,2,3)
>> plot(x,sin(3*x));
>>
>> subplot(2,2,4)>> plot(x,sin(4*x));
Multiple plots
You can assign different line styles to each data set by passing line style identifier strings to
plot and placing a legend on the plot to identify curves drawn with different symbol and line
types.
Example 4.6
>> x = linspace(0,2*pi);
>> y1 = sin(x);
>> y1 = cos(x);
>> y1 = tan(x);
>> plot(x,y1,x);>> axis([0 2*pi -1 1]);
The hold Function
The hold command will add new plots on top of previously existing plots.
Example 4.6
>> x = -pi:pi/20:pi;
>> y1 = sin(x);
>> y2 = cos(x);
>> plot(x,y1,'b-');
>> hold on;
>> plot(x,y2,'g--');
>> hold off;>> legend('sin(x)','cos(x)');
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
26/34
CHAPTER 4: Plotting and Visualization
23
Plotting in MATLAB
Line Plots in Three-Dimensions
Now, the three-dimension analog of the plot function is plot3. ifx,y andz are three vectors
of the same length, plot3(x,y,z) generates a line in 3-D through the points whose coordinates
are the elements ofx,y andz and then produces a 2-D projection of that line on the screen.
Example 4.7
>> Z = [0 : pi/50 : 10*pi];
>> X = exp(-.2.*Z).*cos(Z);
>> Y = exp(-.2.*Z).*sin(Z);
>> plot3(X,Y,Z,'LineWidth',2);
>> grid on;
>> xlabel('x-axis');
>> ylabel('y-axis');>> zlabel('z-axis');
Three-Dimensional Surface Mesh Plots
The first step in displaying a function of two variables, z = f(x,y), is to generate X and Y
matrices consisting of repeated rows and columns, respectively, over the domain of the function.
Then use these matrices to evaluate and graph the function. Meshgrid function transforms the
domain specified by two-vectors,x andy, into matricesXand Y.
Example 4.8
>> [X,Y] = meshgrid(-8:.5:8);
>> R = sqrt(X.^2 + Y.^2);
>> Z = sin(R)./R;>> mesh(X,Y,Z);
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
27/34
CHAPTER 4: Plotting and Visualization
24
Images in MATLAB
Images in MATLAB
The basic data structure in MATLAB is the array, an ordered set of real or complex
elements. Thus, MATLAB stores most images as two-dimensional arrays (i.e., matrices), inwhich each element of the matrix corresponds to a single pixel in the displayed image. For
example, an image composed of 200 rows and 300 columns or different colored dots would be
stored in MATLAB as a 200-by-300 matrix. Some images, such as RGB, require a three-
dimensional array, where the first plane in the third dimension represents the red pixel intensities,
the second plane represents the green pixel intensities, and the third plane represents the blue
pixel intensities.
This example reads an 8-bit RGB image into MATLAB and converts it to a grayscale image.
Example 4.9
>> rgb_img = imread('ngc6543a.jpg');
>> image(rgb_img);
>> pause;
>> graysc_img = rgb2gray(rgb_img);>> imshow(graysc_img);
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
28/34
CHAPTER 5: Programming
25
Data Types
CHAPTER 5
Programming
Data Types
There are many different types of data that you can work with in MATLAB. You can build
matrices and arrays of floating point and integer data, characters and strings, logical true and
false states, etc. you can also develop your own data types using MATLAB classes. Two of the
MATLAB data types, structures and cell arrays, provide a way to store dissimilar types of data in
the same array.
There are 15 fundamental data types (or classes) in MATLAB. Each of these data types is in
the form of an array. This array is a minimum of 0-by-0 in size and can grow to an n-dimensional
array of any size. Two-dimensional versions of these arrays are called matrices. All of the
fundamental data types are shown in lowercase text in the diagram below. Additional data types
are user-defined, object-oriented user classes (a subclass of structure), and java classes, that you
can use with the MATLAB interface to Java. Matrices of type double and logical may be either
full or sparse. For matrices having a small number of nonzero elements, a sparse matrix requires
a fraction of the storage space required for an equivalent full matrix. Sparse matrices invoke
special methods especially tailored to solve sparse problems.
logical char CELL structure JavaClasses
Functionhandle
int8, unit8,
int16, uint16,
int32, uint32,int64, uint64
single double
NUMERIC
ARRAY
(full or sparse)
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
29/34
CHAPTER 5: Programming
26
The following table describes these data types in more detail.
Data type Example Descriptionint8, unit8,
int16, uint16,
int32, uint32,int64, uint64
int16(100) Signed and unsigned integer arrays that are 8, 16,
32, and 64 bits in length. Enables you to manipulate
integer quantities in a memory efficient manner.
These data types cannot be used in mathematical
operations.char 'Hello' Character array (each character is 16 bits long). This
array is also referred to as a string.logical magic(4) > 10 Logical array. Must contain only logical 1 (true) and
logical 0 (false) elements. (Any nonzero values
converted to logical become logical 1.) Logical
matrices (2-D only) may be sparse.single 3*10^38 Single-precision numeric array. Single precision
requires less storage than double precision, but hasless precision and a smaller range. This data type
cannot be used in mathematical operations.double 3*10^300
5+6iDouble-precision numeric array. This is the most
common MATLAB variable type. Double matrices
(2-D only) may be sparse.cell {17 'hello'
eye(2)}Cell array. Elements of cell arrays contain other
arrays. Cell arrays collect related data and
information of a dissimilar size together.structure a.day = 12;
a.color = 'Red';
a.mat = magic(3);
Structure array. Structure arrays have field names.
The fields contain other arrays. Like cell arrays,
structures collect related data and informationtogether.
function
handle
@humps Handle to a MATLAB function. A function handle
can be passed in an argument list and evaluated
using fevaluser class inline('sin(x)') MATLAB class. This user-defined class is created
using MATLAB functions.java class java.awt.Frame Java class. You can use classes already defined in
the Java API or by a third party, or create your own
classes in the Java language.
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
30/34
CHAPTER 5: Programming
27
M-File Programming
MATLAB provides a full programming language that enables you to write a series of
MATLAB statements into a file and then execute them with a single command. You write your program in an ordinary text file, giving the file a name offilename.m. The term you use for
filename becomes the new command that MATLAB associates with the program. The file
extension of .m makes this a MATLAB M-file. M-files can be scripts that simply execute a series
of MATLAB statements, or they can be functions that also accept arguments and produce output.
You create M-files using a text editor, then use them as you would any other MATLAB function
or command. The process looks like this:
Kinds of M-files
There are two kinds of M-files
Script M-files Function M-files
Do not accept input arguments or return output
arguments
Can accept input arguments and return output
argumentsOperate on data in the workspace Internal variables are local to the function by
default
Useful for automating a series of steps you
need to perform many times
Useful for extending the MATLAB language
for you application
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
31/34
CHAPTER 5: Programming
28
Scripts
Scripts are the simplest kind of M-file because they have no input or output arguments.
They're useful for automating series of MATLAB commands, such as computations that you
have to perform repeatedly from the command line. Scripts operate on existing data in theworkspace, or they can create new data on which to operate. Any variables that scripts create
remain in the workspace after the script finishes so you can use them for further computations.
Example 5.1
% An M-file script to produce % Comment lines
% "flower petal" plots
theta = -pi:0.01:pi; % Computations
rho(1,:) = 2*sin(5*theta).^2;
rho(2,:) = cos(10*theta).^3;
rho(3,:) = sin(theta).^2;for k = 1:3
polar(theta,rho(k,:)) % Graphics output
pauseend
Try entering these commands in an M-file called petals.m. This file is now a MATLAB
script. Typing petals at the MATLAB command line executes the statements in the script.
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
32/34
CHAPTER 5: Programming
29
Functions
Functions are M-files that accept input arguments and return output arguments. They operate
on variables within their own workspace. This is separate from the workspace you access at the
MATLAB command prompt.
Example 5.2
If you would like, try entering these commands in an M-file called average.m. The average
function accepts a single input argument and returns a single output argument. To call the
average function, enter
function y = average(x)
% AVERAGE Mean of vector elements.
% AVERAGE(X), where X is a vector, is the mean of vector elements.
% Nonvector input results in an error.
[m,n] = size(x);
if (~((m == 1) | (n == 1)) | (m == 1 & n == 1))
error('Input must be a vector')end
y = sum(x)/length(x); % Actual computation
>> z = 1:99;
>> average(z)
ans =50
The Function Definition Line
The function definition line informs MATLAB that the M-file contains a function, andspecifies the argument calling sequence of the function. The function definition line for the
average function is
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
33/34
CHAPTER 5: Programming
30
All MATLAB functions have a function definition line that follows this pattern.
The Function Name - MATLAB function names have the same constraints as variable
names. The name must begin with a letter, which may be followed by any combination of letters,
digits, and underscores. Making all letters in the name lowercase is recommended as it makes
your M-files portable between platforms.
Flow Control
MATLAB has several flow control constructs:
1. if2. continue3.
break4. switch and case
5. for6. while
If
The if statement evaluates a logical expression and executes a group of statements when the
expression is true. The optional elseif and else keywords provide for the execution of alternate
groups of statements. An end keyword, which matches the if, terminates the last group of
statements. The groups of statements are delineated by the four keywords--no braces or brackets
are involved.
IF expressionstatements
ELSEIF expressionstatements
ELSEstatements
END
Continue
The continue statement passes control to the next iteration of the for or while loop in
which it appears, skipping any remaining statements in the body of the loop. In nested loops,
continue passes control to the next iteration of the for orwhile loop enclosing it.
Break
The break statement lets you exit early from a for orwhile loop. In nested loops, break exits
from the innermost loop only.
-
8/6/2019 MATLAB Tutorial of Fundamental Programming
34/34
CHAPTER 5: Programming
Switch and Case
The switch statement executes groups of statements based on the value of a variable or
expression. The keywords case and otherwise delineate the groups. Only the first matching case
is executed. There must always be an end to match the switch.
SWITCH expressionCASE expression
statementsCASE expression
statementsOTHERWISE
statementsEND
For
The for loop repeats a group of statements a fixed, predetermined number of times. A
matching end delineates the statements.
While
The while loop repeats a group of statements an indefinite number of times under control of a
logical condition. A matching end delineates the statements.
FOR variable = expression
Statements, ...StatementsEND
WHILE expressionStatements
END