You are on page 1of 15

What is MATLAB?

The name MATLAB stands for MATrix LABoratory. MATLAB is a high-performance language for technical
computing. It integrates computation, visualization, and programming environment. Furthermore, MATLAB is a
modern programming language environment: it has sophisticated data structures, contains built-in editing and
debugging tools, and supports object-oriented programming. It also has easy to use graphics commands that make
the visualization of results immediately available. These factors make MATLAB an excellent tool for teaching and
research.

Getting started
1. Starting MATLAB
When you start MATLAB, a special window called the MATLAB desktop appears. The desktop is a window that
contains other windows. The major tools within or accessible from the desktop are:

 The Command Window

 The Command History

 The Workspace

 The Current Directory

 The Help Browser

 The Start button


2. Keeping track of your work session
It is possible to keep track of everything done during a MATLAB session with the “diary” command.
>> diary FileName
You can give a name to the created file, where “FileName” could be any arbitary name you choose.
The function “diary” is useful if you want to save a complete MATLAB session. They save all input and output
as they appear in the MATLAB window. When you want to stop the recording, enter “diary off”. If you
want to start recording again, enter “diary on”. The file that is created is a simple text fie. It can be opened by
an editor or a word processing program and edited to remove extraneous material, or to add your comments.
3. Using MATLAB as a calculator
As an example of simple interactive calculation, just type the expression you want to evaluate. For example, if you
want to calculate an expression, you type it at the prompt command as follows,
>> 1+2*3
ans = 7
You will have noticed that if you do not specify an output variable, MATLAB uses a default variable “ans”,
short for “answer,” to store the results of the current calculation. Note that the variable “ans”is created (or
overwritten, if it is already existed). To avoid this, you may assign a value to a variable or output argument name.
For example,
>> x = 1+2*3
x = 7
This variable name can always be used to refer to the results of the previous computations. Therefore, computing 4x
will result in
>> 4*x
ans = 28
4. Suppressing output
If you do not wish to see the intermediate results, you can suppress the numerical output by putting a semicolon ( ;)
at the end of the line. Then the sequence of commands looks like this:
>> t=-13; u=5*t, v=t^2+u
y =
-65
z =
104
the value of “t” is hidden. Note also we can place several statements on one line, separated by commas ( ,) or
semicolons ( ;).
5. Managing the workspace
The contents of the workspace persist between the executions of separate commands. Therefore, it is possible for the
results of one problem to have an effect on the next one. To avoid the possibility, it is good idea to issue a clear
command at the start of each new independent calculation.
>> clear
The command “clear” or “clear all” removes all variables from the workspace. This frees up system
memory.
6. Miscellaneous commands
Here are few additional useful commands:
 To clear the Command Window, type “clc”
 To abort a MATLAB computation, enter <ctrl-c>

 To continue a line, type . . .


7. Getting help
Because MATLAB is a huge program; it is impossible to cover all the details of each function one by one. After you
grasp the basic facts about Matlab, you can use the help features and documentation.
To view the general help documentation, select “MATLAB Help” from Help menu or “MATLAB Help” directly
in the Command Window. The preferred method is to use the Help Browser. The Help Browser can be started by
selecting the ? icon from the desk-top toolbar. On the other hand, if you want to know information about any
particular command, there are several ways to do this:
 Use “help” to request info on a specific function. For example, to see how to use the “sqrt” function, type
>> help sqrt
 In the current version of MATLAB, the “doc” function opens the on-line version of the help menu. This is very helpful
for more complex commands.
>> doc plot
 Use “lookfor” to find functions by keywords. The general form is
>> lookfor functionkeyword
The “lookfor” command differs from the “help” command. The “help” command searches for an
exact function name match, while the “lookfor” command searches the quick summary information in each
function for a match.
Mathematical functions
MATLAB offers many predefined mathematical functions for technical computing. Typing “help
elfun” and “help specfun” calls up full lists of elementary and special functions respectively.
These long lists of mathematical functions are built into MATLAB. These functions are called “built-ins.” Many
standard mathematical functions, such as sin(x), cos(x), e-+x, tan(x), ln(x), are evaluated by the
functions sin, cos, tan, exp, and log respectively in MATLAB.
Example 1
The value of an expression can be calculated for the given values of a = 5, x = 2, and y = 8.
>> a = 5; x = 2; y = 8;
>> z = exp(-a)*sin(x)+10*sqrt(y)
z =
28.2904
Example 2
The roots of a quadratic equation, ax 2 + bx + c = 0 for a = 2, b = 1, and c = -4 is computed by
>> a = 2; b = 1; c = -4;
>> x1 = (-b+sqrt(b^2-4*a*c))/(2*a)
x1 =
1.1861
>> x2 = (-b-sqrt(b^2-4*a*c))/(2*a)
x2 =
-1.1861
We can press the up arrow key on the keyboard to recall the previous command. Then move the cursor left and
delete the +, and type – in its place, press return.
Example 3
>> log(142)
ans =
4.9558
>> log10(142)
ans =
2.1523
Note the difference between the natural logarithm log(x) and the decimal logarithm (base 10) log10(x).

Example 4
>> sin(pi/4)
ans =
0.7071
>> exp(10)
ans =
2.2026e+004
Matrix generation
MATLAB is an efficient computer programming language if objects in your programs are matrices and vectors. It
stores numerical objects as matrices and it allows users to create and manipulate matrices in a wide variety of ways.
It even treats a scalar as a 1 by 1 matrix. If your programming involves matrices you will find MATLAB to be easily
programmable and very helpful for your computations. Therefore, we need to become familiar with matrix
generation and manipulation.
1. Entering a matrix
A matrix is an array of numbers. To type a matrix into MATLAB you must

 begin with a square bracket, [

 separate elements in a row with spaces or commas (,)

 use a semicolon (;) to separate rows

 end the matrix with another square bracket, ]


Here is a typical example. To enter a matrix A, type,
>> A = [1 2 3; 4 5 6; 7 8 9]
MATLAB then displays the 3 by 3 matrix as follows,
A =
1 2 3
4 5 6
7 8 9
2. Matrix indexing
Once we have entered the matrix, it is automatically stored and remembered in the Workspace. We can the view a
particular element in a matrix by specifying its location. For example, A(1,3) is an element of first row and third
column. We type,
>>A(1,3)
ans =
3
3. Colon operator in a matrix
The colon operator will prove very useful and understanding how it works is the key to efficient and convenient
usage of MATLAB. The colon operator can be used to pick out a certain row or column. For example, the
statement “A(m:n,k:l)” specifies portions of a matrix: rows m to n and column k to l. Here are some
examples.
>> A(2:3,2:3)
ans =
5 6
8 9
is rows 2 and 3 and columns 2 and 3 of the matrix A.
>> A(2,:)
ans =
4 5 6
is the second row element of matrix A.
>> A(:,2:3)
ans =
2 3
5 6
8 9
is a sub-matrix with the last two columns of A.
>> A(2:end,:)
ans =
4 5 6
7 8 9
is sub-matrix with the last two columns of A. The keyword “end”, used here, denotes the last index in the
specified dimension. For example, “A(end,:)” picks out the last row of A.
4. Transposing a matrix
The transpose operation is denoted by an apostrophe or a single quote (‘). It flips a matrix about its main diagonal
and it turns a row vector into a column vector. Thus,
>> A'
ans =
1 4 7
2 5 8
3 6 9
5. Concatenating matrices
Matrices can be made up of sub-matrices. Here is an example. A new matrix B will be,
>> B = [A 10*A; -A [1 0 0; 0 1 0; 0 0 1]]
B =
1 2 3 10 20 30
4 5 6 40 50 60
7 8 9 70 80 90
-1 -2 -3 1 0 0
-4 -5 -6 0 1 0
-7 -8 -9 0 0 1
6. More on generating vectors
1. Colon operator
Often we must deal with matrices or vectors that are too large to enter one element at a time. For example, suppose
we want to enter a vector x consisting of points (0, 0.1, 0.2, 0.3,… , 5). We can use the
command
>> x = 0:0.1:5;
The row vector has 51 elements. The first and the last element are 0 and 5, and all the elements in between increase
by one-tenth.
2. Linear spacing
On the other hand, there is a command to generate linearly spaced vectors: “linspace”. It is similar to the
colon operator (:), but gives direct control over the number of points. For example,
y = linspace(a,b,n)
generates a row vector “y” of “n” points linearly spaced between and including “a” and “b”. This is useful
when we want to divide an interval into a number of subintervals of the same length. Here is an example,
>> theta = linspace(0,2*pi,101);
divides the interval into 100 equal subintervals, then creating a vector of 101 elements.
3. Elemetary matrix generators
MATLAB provides functions that generate elementary matrices. The table below gives a number of them. For a
complete list of elementary matrices and matrix manipulations, type “help elmat” or “doc elmat”.
Table 1. Elementary matrices

eye(m,n) Returns an m-by-n matrix with 1 on the main


diagonal

eye(n) Returns an n-by-n square identity matrix

zeros(m,n) Returns an m-by-n matrix of zeros

ones(m,n) Returns an m-by-n matrix of ones

diag(A) Extracts the diagonal of matrix A

rand(m,n) Returns an m-by-n matrix of uniformly


distributed random numbers

randn(m,n) Returns an m-by-n matrix of normally


distributed random numbers

logspace(a,b,n) Row vector with logarithmically spaced


entries

Matrices and array operations


1. Overview
MATLAB has two different types of arithmetic operations: matrix arithmetic operations and array arithmetic
operations.
2. Matrix operations
1. Arithmetic operations
MATLAB allows arithmetic operations: +, -, *, and ^ to be carried out on matrices. Thus,

Table 2. Matrix arithmetic operations

A+B or B+A is valid if A and B are of the same


size

A*B is valid if A’s number of column


equals B’s number of rows

A^2 is valid if A is square and equals A*A

a*A or A*a multiplies each element of A by a

2. Matrix functions
MATLAB provides many matrix functions for various matrix / vector manipulations. Let’s consider a matrix A.
Calculating the inverse of A manually is probably not a pleasant work. In MATLAB, however, it becomes as simple
as the following commands:
>> A = [1 2 3; 4 5 6; 7 8 0];
>> inv(A)
ans =
-1.7778 0.8889 -0.1111
1.5556 -0.7778 0.2222
-0.1111 0.2222 -0.1111
In linear algebra, to calculate A -1 B, we need to use the matrix inverse, “inv”
>> inv(A)*B
The second way to solve this is to use the backslash(\) operator.
>> A\B
Note: the usage of slash (/) operator, A/B, is to calculate: A B -1.
The determinant of A is
>> det(A)
ans =
27
See the table below for more of these functions. Use the help documentation of MATLAB to find how to use these
functions.

Table 3. Matrix functions

det Determinant

diag Diagonal matrices and diagonals of a


matrix

eig Eigenvalues and eigenvectors

inv Matrix inverse

norm Matrix and vector norms

rank Number of linearly independent rows


or columns

3. More on matrix operations


Here are some examples that involve the use of the colon operator.
>> sum(A(2,:))
calculates the sum of elements in the second row of matrix A.
>> sum(A(:,end))
calculates the sum of the last column of A.
2. Array operations
Array arithmetic operations or array operations for short, are done element-by-element.
The “period” character ( .) distinguishes the array operations from the matrix operations. However, since
the matrix and array operations are the same for addition ( +) and subtraction ( -), the character pairs (
.+) and ( .-) are not used. Here are some simple examples.
If A and B are two matrices of the same size with elements A = [ a ij ] and B = [ b ij ], then the command
>> C = A.*B
produces another matrix C of the same size with elements c ij = a ijb ij .
If we want to produce another matrix C of the same size with elements c ij = a ij / b ij , enter
>> C = A./B
If we want the operation produce a new matrix whose elements are the square of the elements of the matrix A, we
enter
>> C = A.^2
this produces another matrix C of the same size with elements c ij = a ij 2.
Reading and writing data files
MATLAB allows a number of different ways to save the data. In this tutorial we explore the different ways that you
can save and read data into a MATLAB session.
1. save and load data file
The area of memory accessible from the command line is called Workspace. As you create variables, they are stored
in the workspace for that session. If you want to save the variable in the workspace, you need to use
command “save”.
>> x = [1 3 -4];
>> y = [2 -1 7];
>> z = [3 2 3];
>> save Filename.mat
This command saves all the variables in the workspace into a binary file “Filename.mat” ( “.mat” is the
default extension for MATLAB data.). Here, “Filename” is an arbitrary file name.
You can also save only certain variables by specifying the variable names after the file name.
>> save Filename.mat x y
If you want to save variables into ASCII data file, type
>> save Filename.dat x y -ascii
The data can be read back in to a MATLAB session with the “load” command.
>> load Filename.mat
In this example, the contents of the entire data file, “Filename.mat”, is then read back into memory. You do
not have to load all of the contents of the file into memory. After you specify the file name you then list the
variables that you want to load separated by spaces. In the following example only the variable “x” will be loaded
into memory.
>> load Filename.mat x
You can also “load” the ASCII data file back into memory,
>> load Filename.dat -ascii
Note: a binary data file is stored in program readable format, so its processing is fast; a text (ASCII) file is stored in
human readable format and can be used to export/import data that can be used in programs other than MATLAB, so
its processing is slow.
2. The “textread” function
In the previous examples, the “load” command (with ASCII option) assumes all of the data is of a single type.
To be more flexible, we need to use the “textread” function. It is designed to read ASCII files that are
formatted into columns of data. Each column can be of a different type. This function is useful for importing tables
of data printed out by other applications.
>> [A,B,C,...] = textread(filename, format, n);
This command reads variables A,B,C,. . . from an ASCII data file filename where the content types of these
variables (i.e. integers, strings, floating numbers) are given by format. The last argument “n”gives the number of
observations that are to be read for the variables A,B,C,. . . . If you do not specify “n” then MATLAB reads all
observations. The filename and format are strings so when entering their values you should enclose them in single
quotes ( ‘).
For example, if you have a text file “mydata.dat” containing the following lines:
tommy 32 male 78.8
sandy 3 female 88.2
alex 27 male 44.4
saul 11 male 99.6
If you type
>> [name,age,gender,score] = textread('mydata.dat', '%
s %d %s %f', 2);
Then MATLAB will create 4 variables each consisting of 2 values because we forced it to read only 2 observations
although there are 4 records. “%s” in the format field indicates that the variable is a string.
Similarly, “%d” indicates that the variable is an integer, “%f” indicates that the variable is a floating point
number.
3. C Style Read/Write
In addition to the high level read/write commands detailed above, MATLAB allows C style file access. When data
are written to or read from a file, it is crucially important that a correct data format is used. The data format is the
key to interpreting the contents of a file and must be known in order to correctly interpret the data. There are two
types of data files: formatted and unformatted. Formatted data files use format strings to define exactly how and in
what positions of a record the data is stored. Unformatted storage, on the other hand, only specifies the number
format.
1. Formatted files
Some computer codes and measurement instruments produce results in formatted data files. In order to read these
results into MATLAB for further analysis the data format of the files must be known. Formatted files in ASCII
format are written to and read from with the commands “fprintf” and “fscanf”.
 fprintf(fid, ‘format’,variables) writes variables in a format specified in the
string “’format’” to the file with identifier “fid”.
 a = fscanf(fid, ‘format’,size) assigns to variable “a” the data read from a file with
identifier “fid” under format “’format’”.
For example, suppose the numeric data is stored in a file “sound.dat”. A set of commands reading data
from “sound.dat” is,
>> fid = fopen(`sound.dat',`r');
>> data = fscanf(fid, `%f');
>> fclose(fid);
Respectively,
 open a file for reading (this is designated by the string “r”). The variable “fid” is assigned a unique integer which
identifies the file used (a file identifier). We use this number in all subsequent references to the file.
 Read the data to a vector named “data”.
 Close the file with file identifier “fid”.
2. Unformatted files
Unformatted or binary data files are used when small sized files are required. In order to interpret an unformatted
data file, the data precision must be specified. The precision is specified as a string, e.g., “float32”,
controlling the number of bits read for each value and the interpretation of those bits as character, integer or floating
point values. Precision “float32”, for instance, specifies each value in the data to be stored as a floating point
number in 32 memory bits.
For example, suppose numerical data is stored as floating point numbers using 32 memory bits. The data is stored on
file “vib.dat”. The following commands illustrate how the data may be read into MATLAB for analysis.
Step 1: Assign a file identifier, “fid1”, to the string specifying the file name.
>> fid1 = fopen('vib.dat','rb');
The string “’rb’” specifies that binary numbers are to be read from the file.
Step 2: Read all the data stored on file “vib.dat” into a vector “vib”.
>> vib = fread(fid1, 'float32');
>> fclose(fid);
Here we have given very simple examples. After you look at this overview we highly recommend that you look
through the relevant help files as well. This will help you to fill in the missing blanks.

Basic plotting
1. Overview
MATLAB has an excellent set of graphic tools. Plotting a given data set or the results of computation is possible
with very few commands. Being able to plot mathematical functions and data freely is the most important step, and
this section is written to assist you to do just that.
2. Plotting elementary functions
The basic MATLAB graphing procedure, for example in 2D, is to take a vector of x-coordinates and a vector of y-
coordinates, locate the pairs of points and then join them by straight lines. You need to prepare “x” and “y” in an
identical array form; namely, ”x” and “y” are both row arrays or column arrays of the same length.
For example, to plot the function “y = sin(x)” on the interval “[0,2pi]”, we first create a vector
of “x” values ranging from 0 to 2pi, then compute the sine of these values, and finally plot the result.
We do this by sampling the function at a sufficiently large number of points and then joining up the points (
x,y) by straight lines. Suppose we take steps (or increments) of pi/100 over the distance [0,2pi]:
>> x = 0:pi/100:2*pi;
The corresponding y values are computed by:
>> y = sin(x);
And finally, we can plot the points with:
>> plot(x,y)
3. Adding titles, axis labels
MATLAB enables you to add axis labels and titles. For example, to include a title and label the axes on the graph
from the previous example, we use:
>> xlabel (`x = 0:2\pi');
>> ylabel (`Sine of x');
>> title (`Plot of the Sine function')
The strings enclosed in single quotes, can be anything of our choosing. The character “\pi” creates the symbol
for pi.
The color of a single curve is, by default, blue, but other colors are possible. The desired color is indicated by a third
argument. For example, red is selected by “plot(x,y,’r’)”.
4. Multiple data sets in one plot
Several graphs may be drawn on the same figure. For example, these statements plot three related function of x: y 1=
2*cos(x), y 2 = cos(x), and y 3 = 0.5*cos(x), in the interval [0 2pi].
>> x = 0:pi/100:2*pi;
>> y1 = 2*cos(x);
>> y2 = cos(x);
>> y3 = 0.5*cos(x);
>> plot(x,y1,'--',x,y2,'-',x,y3,':')
>> xlabel('0 \leq x \leq 2\pi')
>> ylabel('Cosine functions')
>> legend('2*cos(x)','cos(x)','0.5*cos(x)')
>> title('Typical example of multiple plots')
5. Subplot
MATLAB allows the graphic window to be split into an m by n array of small windows into which we may plot one
or more graphs. The windows are counted 1 to mn row-wise, starting from the top left. For example, these
statements subplot four related function of x: y 1 = sin(3pi*x), y 2= cos(3pi*x), y 3 = sin(6pi*x), and y 4 = cos(6pi*x)
in the interval [0 1].
>> x = 0:1/100:1;
>> y1 = sin(3*pi*x);
>> y2 = cos(3*pi*x);
>> y3 = sin(6*pi*x);
>> y4 = cos(6*pi*x);
>> title('Typical example of subplots')
>> subplot(2,2,1), plot(x,y1)
>> xlabel('0 \leq x \leq 1'), ylabel('sin(3 \pi x)')
>> subplot(2,2,2), plot(x,y2)
>> xlabel('0 \leq x \leq 1'), ylabel('cos(3 \pi x)')
>> subplot(2,2,3), plot(x,y3)
>> xlabel('0 \leq x \leq 1'), ylabel('sin(6 \pi x)')
>> subplot(2,2,4), plot(x,y4)
>> xlabel('0 \leq x \leq 1'), ylabel('cos(6 \pi x)')
“subplot(2,2,1)” specifies that the window should be split into a 2 by 2 array and we select the first
subwindow.
Introduction to programming in MATLAB
1. Introduction
So far, all the commands were executed in the Command Window. The problem is that the commands entered in the
Command Window cannot be saved and executed again several times. In order to repeat any calculation and/or
make any adjustments, it is most convenient to create a file with a list of commands. The files that are used for this
purpose are called script files or scripts for short.
This section covers the following topics:

 M-File Scripts

 M-File Functions
2. M-File scripts
An M-File script is an external file that contains a sequence of MATLAB statements. Script files have a filename
extension “.m” and are often called M-Files. M-Files can be scripts that simply execute a series of MATLAB
statements, or they can be functions that can accept arguments and can produce one or more outputs.
Note: the first character of the filename must be a letter.
Examples
Here are some simple scripts.
Example 1
Let’s put the commands for calculating the roots of a quadratic equation into a file called “quat.m”.
 Use the MATLAB editor to create a file: “File –> New –> M-file“.

 Enter the following statements in the file:


a = 2;
b = 1;
c = -4;
x1=(-b+sqrt(b^2-4*a*c))/(2*a)
x2=(-b-sqrt(b^2-4*a*c))/(2*a)
 Save and name the file, for example, “quat.m”.
 Run the file, by typing “quat” at the MATLAB command line prompt:
>>quat
x1 =
1.1861
x2 =
-1.1861
Example 2
It is possible to modify the file “quat.m” so that it prompts you for inputting values of a, b, and c each time it
runs. Here is the modified version of the file:
a = input(`Enter a: ');
b = input(`Enter b: ');
c = input(`Enter c: ');
x1=(-b+sqrt(b^2-4*a*c))/(2*a)
x2=(-b-sqrt(b^2-4*a*c))/(2*a)
When “quat.m” is re-run, you may type in the values for a, b, and c.
>>quat
Enter a: 3
Enter b: 4
Enter c: 5
x1 =
-0.6667 + 1.1055i
x2 =
-0.6667 - 1.1055i
Here the “i” after a number represents square root of -1.
Example 3
MATLAB treats everything that appears after the % on a line as comments and these lines will be ignored when the
M-file runs. We can further modify quat.m to be the following:
% ----------------------------------------------------
---
% quat.m is to solve quadratic equation ax^2 + bx + c
=0
% ----------------------------------------------------
---
a = input(`Enter a: ');
b = input(`Enter b: ');
c = input(`Enter c: ');
x1=(-b+sqrt(b^2-4*a*c))/(2*a)
x2=(-b-sqrt(b^2-4*a*c))/(2*a)
You can display the first block of comment lines in any “.m” file by issuing the “help” command. Here is
what you get from typing “help quat”.
>> help quat
% ----------------------------------------------------
---
% quat.m is to solve quadratic equation ax^2 + bx + c
=0
% ----------------------------------------------------
---
3. M-File functions
Functions are programs (or routines) that accept input arguments and return output arguments.
The main steps to follow when defining a MATLAB function are:

 Decide on a name for the function, making sure that it does not conflict a name that is already used by MATLAB.
 Document the function. That is, describe briefly the purpose of the function and how it can be used. Each comment line
should be preceded by a “%” which signifies that the line should be ignored when the function is evaluated.

 The first command line of the file must have the format:
function
= functionname(list of inputs)
......
......
 Save the function as a M-file
Examples
Here are some simple examples.
Example 1
Using our previous M-File example (solving the quadratic equation), if it is being used by many other M-files, it will
be convenient to have a separate file (i.e. a function file) which calculates the roots of a quadratic equation. Let’s
write a function file “quatsol.m”:
% ----------------------------------------------------
------
% quatsolv.m is to compute the roots of
% quadratic equation ax^2 + bx + c =0
% ----------------------------------------------------
------
function [x1, x2] = quatsolv(a, b, c)
x1=(-b+sqrt(b^2-4*a*c))/(2*a);
x2=(-b-sqrt(b^2-4*a*c))/(2*a);
The first line of a function M-File starts with the keyword “function”. (Notice above that Matlab ignores the
comment lines so the first executable statement is the “function” statement.) It gives the function name and
order of arguments. In this example, there are up to two output arguments and three input arguments.
To evaluate this function, a main program is needed. This main program provides input arguments (a, b, and c).
These inputs are then sent to the function file (“quatsolv.m”) to calculate the roots and then return the results
back to the main program. In this example, the main function is to be called “main.m”, which looks like:
% ----------------------------------------------------
---
% main.m is to solve quadratic equation ax^2 + bx + c
=0
% it calls the external function quatsolv.m
% ----------------------------------------------------
---
a = input(`Enter a: ');
b = input(`Enter b: ');
c = input(`Enter c: ');
[x1, x2] = quatsolv(a, b, c);
x1
x2
When “main.m” is invoked, it will function as the previous version of “quat.m”.
Example 2
Besides solving the quadratic equation on roots of a quadratic equation, one can also plot it for a graphical
presentation. Let’s create another main file ( “main2.m” ) and a new function file ( “quatsolv2.m” )
which look like the following:
% ----------------------------------------------------
---
% main2.m is to plot quadratic equation ax^2 + bx + c
for
% some range.
% it calls the external function quatsolv2.m
% ----------------------------------------------------
---
global a b c
a = 1;
b = 0;
c = -2;
fplot(`quatsolv2',[-4, 4])
The global statement means that a, b, and c can be used outside of main2.m. In the “fplot”statement, the single
quotes around “quatsolv2” are necessary to prevent MATLAB from evaluating ”quatsolv2” until
inside “fplot”. The second argument of “fplot”, “[-4,4]”, is a vector which defines the beginning
and the end of the range of x-values over the plot. The function file “quatsolv2.m” is defined as the
following:
% ----------------------------------------------------
------
% quatsolv2.m is to compute the values of
% quadratic equation ax^2 + bx + c
% ----------------------------------------------------
------
function y = quatsolv2(x)
global a b c
y = a*x^2 + b*x + c;
In this example, there are up to one output argument and one input argument. If you run “main2.m”, a graph
will show as below:

Figure 1.

You might also like