Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
38 views

1 Basic Element of Matlab

This document provides an overview of basic elements in MATLAB, including: 1) What MATLAB is and its main uses like matrix computations and data visualization. 2) How to start and stop MATLAB and descriptions of the main windows. 3) How to enter commands in MATLAB, use variables, suppress output, and continue commands over multiple lines. 4) Help facilities, arrays, graphs, script files, user-defined functions, and saving/loading data.

Uploaded by

Suman Senden
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

1 Basic Element of Matlab

This document provides an overview of basic elements in MATLAB, including: 1) What MATLAB is and its main uses like matrix computations and data visualization. 2) How to start and stop MATLAB and descriptions of the main windows. 3) How to enter commands in MATLAB, use variables, suppress output, and continue commands over multiple lines. 4) Help facilities, arrays, graphs, script files, user-defined functions, and saving/loading data.

Uploaded by

Suman Senden
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

(Most contents are from Matlab Course of University of Technology, Eindhoven.

Basic elements of MATLAB

Contents
1 What is MATLAB?...................................................................................................................... 3

2 Starting and stopping ................................................................................................................... 4

3 Commands in MATLAB ............................................................................................................. 6

3.1 Mathematical expressions ..................................................................................................... 7

3.2 Interruption ........................................................................................................................... 9

3.3 Incomplete commands .......................................................................................................... 9

3.4 Variables ............................................................................................................................... 9

4 Help facilities ............................................................................................................................. 11

4.1 Use of the Help Browser ..................................................................................................... 12

4.2 The best way to search ........................................................................................................ 13

5 Arrays ......................................................................................................................................... 14

5.1 Array operations.................................................................................................................. 16

5.2 Producing an array of function values ................................................................................ 18

5.3 Relational array operations ................................................................................................. 19

5.4 Other array operations......................................................................................................... 20

5.5 Transposition....................................................................................................................... 21

Asst. Prof. Sachin Shrestha 1


6 Graphs ........................................................................................................................................ 22

6.1 Other graph types ................................................................................................................ 24

7 Script m-Files ............................................................................................................................. 26

7 User defined functions ............................................................................................................... 27

7.1 Function m-files .................................................................................................................. 27

7.2 Anonymous functions ......................................................................................................... 28

8 Saving and loading data ............................................................................................................. 29

9 Exercises .................................................................................................................................... 31

Exercise 1.1: Entering commands............................................................................................. 31

Exercise 1.2: Interruption of calculations or output.................................................................. 31

Exercise 1.3: Incomplete commands ........................................................................................ 31

Exercise 1.4: Removal of variables .......................................................................................... 32

Exercise 1.5: Saving data files .................................................................................................. 32

Exercise 1.6 ............................................................................................................................... 32

Exercise 1.7 ............................................................................................................................... 32

Exercise 1.8 ............................................................................................................................... 32

Exercise 1.9 ............................................................................................................................... 33

Asst. Prof. Sachin Shrestha 2


1 What is MATLAB?

MATLAB is a computer program designed for technical calculations. Its name is an abbreviation
of "Matrix Laboratory". In this program, matrix computations are implemented in a
straightforward manner. However, many other pre-programmed routines are available. In addition,
it is possible to implement user-defined calculation routines. MATLAB allows users to implement
calculations in relatively short programming time. When these calculations have been performed,
they can be visualized by means of several plot-routines.

MATLAB can be extended with so called toolboxes. In general, these are collections of MATLAB
functions that are tailored for special classes of problems. The ‘(Extended) Symbolic Math
Toolbox’ is an exception. To a great extent, this toolbox consists of ingredients from the computer
algebra package MuPAD. MATLAB performs calculations with the aid of matrices. These are
rectangular schemes of numbers, which are also called arrays. The `Symbolic Math Toolbox' is
quite different from MATLAB itself, since symbolic calculations hardly make any use of arrays.
For this reason it is important to know whether a function used is a MATLAB function or a
`Symbolic Math Toolbox' function. This will not be completely clear at the outset, but it will
become clearer after regular use of MATLAB.

Asst. Prof. Sachin Shrestha 3


2 Starting and stopping

MATLAB can be started by clicking on the selecting the "MATLAB" option in your startup tree
or possible on your Windows desktop. When MATLAB is started, a window similar to the one
below should appear:

The main window in MATLAB is the command window, positioned at the lower right cornor, in
which commands can be typed after the MATLAB prompt:

>>

Commands are entered with the ‘return’ key. The command is then executed by MATLAB. If
MATLAB is ready, after possible outputs a new prompt appears.

The window on the left is the "Current Folder" window. The "Current Folder" window depicts the
files in the current directory. This is the first user-governed directory where MATLAB will look
for files or functions. On the top right you will find the "Workspace" window, in which all declared
variables are shown. The bottom right window is the "Command history", where you can find all

Asst. Prof. Sachin Shrestha 4


commands you have (recently) entered. By double-clicking on such a command, MATLAB reuses
the command.

Stopping MATLAB can also be done in different ways:

 By means of the command:


>> quit

 Via the menu File \ Exit MATLAB


 Clicking on the cross in the upper right of your window.

Asst. Prof. Sachin Shrestha 5


3 Commands in MATLAB

By clicking on the "Command Window", after the MATLAB prompt >>, a command can be typed.
After having pushed the ‘return’ key, the command is executed, and possibly the result appears on
the screen. A command and its result looks like this:

>> a = 1 + 2 + 3
a =
6

The result of 1 + 2 + 3 is assigned to the variable a. You can now use this variable in successive
operations, such as:

>> b = 2*a + a/3


b =
14

In MATLAB, variables are introduced by assigning a value. Note, that the value can be numerical
values, matrices (called arrays), or other types. You can use the variable, and later possibly assign
a new value to the variable. It is not possible to perform calculations with variables that have not
been assigned a value.

A command does not need to start with an assignment of the form variable =. In such a case, the
result is automatically assigned to the variable ans. You can then use ans further.

>> 4*a + 1
ans =
25
>> ans*ans
ans =
625

If you now want to know what the value of a is, the following command suffices:

>> a
a =
6

Normally, MATLAB displays the output below the command. The output is suppressed by ending
the command with a semicolon. After having entered the command s=1+2, the screen looks as
follows

Asst. Prof. Sachin Shrestha 6


>> s = 1 + 2;

The value 3 has been assigned to the variable s. If you want to know the value of this variable, you
can either look in the “Workspace” window on the top left of your MATLAB window, or request
the value of s as follows

>> s
s =
3

If a command is longer than one line, you can end the line with three dots, and then press the
‘return’ key. You can then continue on the following line. After completing the command, the
screen looks as follows:

>> s = 1 + 2 + ...
3 + 4
s =
10

3.1 Mathematical expressions

You cannot enter mathematical expressions literally. The Tables 1.1-1.2 make clear how
mathematical expressions can be entered. The variables in these tables are to be interpreted as
numbers.

Table 1.1: Standard operations


MATLAB Standard
a+b a+b
a-b a-b
a*b ab
a/b a/b
a^b ab

Asst. Prof. Sachin Shrestha 7


Table 1.2: Mathematical operations
MATLAB Standard
sin(x) Sin(x)
sqrt(x) √x
cos(x) Cos(x)
exp(x) ex
tan(x) Tan(x)
log(x) Ln(x)
asin(x) Sin-1(x)
log10(x) Log10(x)
acos(x) Cos-1(x)
abs(x) |x| ,i.e. absolute value of
atan(x) Tan-1(x)
sign(x) sign( )
mean(x) mean( )
std(x) standard deviation min(x)
max(x) max( )
returns (a x b) array of random numbers, distributed
rand(a,b)
uniformly in [0,1] *
returns (a x b) array of random numbers, distributed
randn(a,b)
normally with mean 0 and variance 1*
round(x) Rounding to nearest integer
floor(x) Rounding to smaller integer
ceil(x) Rounding to larger integer
* Omitting b yields a x a array and
omitting a, b yields a single number

Remark: The order of operations in MATLAB is the standard order: first raising to a power, then
multiplication and division, and after that addition and subtraction. To deviate from this sequence,

Asst. Prof. Sachin Shrestha 8


parentheses ‘(‘ and ‘)’ need to be used to define the order of calculations, e.g. is
obtained by running 1/(exp(3)+1).

3.2 Interruption

A (long) MATLAB calculation can be interrupted with ‘ctrl-c’. After this, a new prompt appears
and new commands can be entered. This interruption is especially useful when a programmed loop
is running that is corrupt.

3.3 Incomplete commands

If a command is incomplete or invalid and you press the `return' key, there are two possibilities:

 An error message and a new MATLAB prompt appear. You can start over again.
 The flickering cursor is at the left of the line below the command. In this case there are two
possibilities.
o The command can be finished and after that evaluated.
o Using ‘ctrl-c’, you can interrupt entering the command. A new MATLAB prompt
appears.

3.4 Variables

The name of a variable in MATLAB has to start with a letter. After that, the name can consist of
an arbitrary number of letters, numbers or symbols like '_' and '-'. MATLAB does distinguish
between upper and lower case letters.

MATLAB uses some special variables, shown in Table 1.3.

Table 1.3: Predefined variables in MATLAB


Variable Explanation
ans This variable contains the result of the last calculation that has not been
assigned to another variable.

Asst. Prof. Sachin Shrestha 9


eps The value of this variable is approximately 2.2204x10-16 and is being used
internally by MATLAB. This number is the default computation accuracy of
MATLAB which is used to round of all numbers for storage in the computer
memory. Do not confuse eps with the number ,

because
i or j The complex number i with the property that i2 = -1.
pi 3.1415...
Inf This is the value infinity. When one divides 1 by 0, 1/0, the result will be Inf.
NaN This variable is a representation of `Not a Number'. A calculation with NaN
always results in NaN. The command 0/0 produces NaN.

Warning: in principle, it is possible to assign a value to the internal MATLAB variables presented
in Table 1.3. This can influence your calculations. Therefore, it is wise never to assign a value to
an internal MATLAB variable. Commands like >>pi=10 should be avoided at all times! If by
accident you have given a different value to an internal MATLAB variable, you can remove this
value by using clear or the workspace browser.

On the top right of the default MATLAB window, you will find the "Workspace" window where
all variables in use are listed. The browser also indicates to which class the variables belong. If
necessary, you can remove variables by using the browser. The special variables above will not be
listed.
Some other important commands for the management of variables are given in Table 1.4.

Table 1.4: Important commands.


Command Explanation
who Gives a list of the variables in use.
whos Gives a list of the variables in use as well as some extra information.
clear Removes all variables.
clear x y Removes the variables x and y .

Asst. Prof. Sachin Shrestha 10


4 Help facilities

In principle all information about MATLAB can be found in MATLAB's help facilities. Since the
MATLAB commands and functions can often be used in more general situations, the information
you will obtain through the help facilities will often be more general than necessary. You will have
to filter out the essential ingredients from the information that is offered.
Below we list the most important ways to use the MATLAB help facilities.

 Help Functions - By typing the command >> help 'function name' in the Command
Window, an M-help file appears in the Command Window. This file contains a short
description of the function, the syntax, and other closely related help functions. This is
MATLAB's most direct help facility, and you will often use this facility to quickly check
how a certain function works and which notation should be used. If more extensive results
are needed, try the command doc.
 Look for - By typing the command lookfor 'topic' in the Command Window, you can
call up all help possibilities which contain the specific search word. You can use this
possibility to look for a function of which you do not remember the function name exactly.
In this manner, all related topics appear in the Command Window.
 Help Browser - You can use the `Help Browser' to find and browse information about
Mathworks products. This help browser contains different ways to obtain the correct
information, like lists, a global index and a search function. You will especially use this
help facility if you are looking for a function of which you do not remember the name.
More information about the Help Browser can be found in the next paragraph.
 Other help facilities - You can use product specific help facilities, have a look at
Mathworks' demos by typing demos in the Command Window, consult the Technical
Support, look for documentation about other Mathworks products, have a look at a list or
other books, and take part in a MATLAB newsgroup. More information about these topics
can be found in the MATLAB Help Browser or on the site www.mathworks.com.

Asst. Prof. Sachin Shrestha 11


4.1 Use of the Help Browser

You can use the "Help Browser" to look for documents and to have a look at MATLAB documents
and other Mathworks products. The "Help Browser" is a html viewer that is integrated in the
MATLAB desktop. With this browser you can look at the HTML documents belonging to
MATLAB.
You can open the "Help Browser" in three different ways:

 By clicking on the help button in the MATLAB task bar.


 By typing helpbrowser or doc in the Command Window.
 By selecting the menu Help \ Product Help in the Menu bar.

When the "Help Browser" is opened, a window similar as the one below will appear:

The Help Browser consists of two parts. The upper part called the Help Navigator/Search box, can
be used to find information. In the lower part you can look at the documentation. Below, the
different tabs of the navigator are listed:

Asst. Prof. Sachin Shrestha 12


 Contents - Within this tab you can browse a list (arranged in a tree structure) with the
contents of the documentation.
 Index - Here, you can find information by entering key words.
 Search results - Above the different tabs, you can enter a search word. Results of your
search will be shown in this tab. Results found in the documentation will be listed
separately from results found in the demos.
 Demos - Within this tab, you can browse through the demos that are present.

4.2 The best way to search

When you know the name of a MATLAB command you want to use, e.g. the function plot, the
fastest way to obtain information is to type

>> help 'function name',

in this case >> help plot.

This will show you some help in the command window. An alternative is to use the command doc
plot that will open the help browser containing a more extensive explanation, sometimes
containing examples.

If you do not know the name of a function or do not know whether such a function exists, using
the command lookfor function or the Help Browser would be appropriate

Asst. Prof. Sachin Shrestha 13


5 Arrays

MATLAB uses matrices (or arrays) as the basic calculation unit. An array is a rectangular scheme
of numbers, called elements, arranged in rows and columns. The simplest array contains
only one column or one row.

An array with one row is also called a row or a row vector, and an array with one column is also
called a column or a column vector. If the difference between consecutive elements in a row is
always the same, the row can be formed with the command:

‘variable’ = ‘initial value’ : ‘step size’ : ‘final value’

Here ‘initial value’ is the first element of the row, ‘final value’ is the last element of the row, and
‘step size’ is the difference between the consecutive elements. For example:

>> x = 1:-0.2:0

gives the row

x =
1.0000 0.8000 0.6000 0.4000 0.2000 0

If the difference between consecutive elements of the row is +1, ‘step size’ can be omitted. For
example,

>> x = 1:5

gives the row

x =
1 2 3 4 5

For arrays with m rows and n columns, the numbers or elements aij are sorted in different rows and
columns:

Asst. Prof. Sachin Shrestha 14


Such an array can be entered in different ways:

 Between ‘[‘ and ‘]’ the elements are separated by spaces or commas, and the rows are
separated by a semicolon. The commands are:

>> a = [1 2 3;4 5 6;7 8 9]

or

>> a = [1,2,3;4,5,6;7,8,9]

 Between ‘[‘ and ‘]’ where the elements are separated by spaces or commas, and each row
is entered on a new line by using the ‘return’ key. The command now is

>> a = [1 2 3
4 5 6
7 8 9]

In each of the cases above, the result is

a =
1 2 3
4 5 6
7 8 9

Elements of arrays can be indicated by means of their index. In the case of row and column vectors,
one index suffices. This can be used according to the Table 1.5.

Table 1.5: Using array indices

MATLAB command Result


a(1,2) Gives the element on the first row and second column of .
a(1,:) Gives the first row of a .
a(:,3) Gives the third column of a .

Asst. Prof. Sachin Shrestha 15


a(:,2)=[10;10;10] Changes the second column of into a column with 10's only.
Only works if a is a n x 3 array, n ≥ 3
b(1) the first element of b in case b contains either one row or one
column.
a(1,[3,1]) an array consisting of the and elements of the first row
of a .

Arrays (both matrices and vectors) can be concatenated into new arrays. If the arrays are arranged
in a row, the number of rows in the arrays have to be equal. If the arrays are arranged in column,
the number of columns in the arrays have to be equal. The concatenation of the arrays a = [2 3
4] and b = [6 5] proceeds as follows:

>> [a,b]

ans =
2 3 4 6 5

5.1 Array operations

An ‘array operation’ is an operation (like addition or subtraction) that is applied to corresponding


elements of two arrays of the same form. When an operation is applied to all elements of one array,
one also speaks of an ‘array operation’.

The operations addition and subtraction are automatically interpreted as array operations. After the
assignments

>> a = [1,2,3]; b = [6,5,4];

Addition of the arrays results in

>> a+b

ans =
7 7 7

And subtraction of the arrays results in

>> a-b

ans =

Asst. Prof. Sachin Shrestha 16


-5 -3 -1

Note that the arrays a and b should be of the same size.

Array operations, such as multiplication ‘*’, division ‘/’ and raising to a power ‘^’, are indicated
by putting a dot ‘.’ in front of the operation sign. In these array operations, the operation is
performed elementwise, e.g. the 1,1-element of a.*b, yields a(1,1)*b(1,1) when a and b are arrays
of appropriate sizes.

Hence

>> a.*b

ans =
6 10 12

>> a./b

ans =
0.1667 0.4000 0.7500

>> a.^b

ans =
1 32 81

For all these operations, the following conventions hold:

1. If in an array operation one of the arrays is a number, this number is interpreted as an array
of which each element equals this number, and of which the size is equal to the size of the
other array.
2. If each element of an array is to be multiplied by a scalar, one does not need to put a dot in
front of the multiplication sign.

Examples:

>> 2.^b

ans =
64 32 16

>> [2 2 2].^b

ans =

Asst. Prof. Sachin Shrestha 17


64 32 16

>> a./2

ans =
0.5000 1.0000 1.5000

>> 3*a

ans =
3 6 9

Detailed information about these operations can be obtained with the command help arith.

5.2 Producing an array of function values

Consider the function.

We want to assign the row vector to the variable y. First we make an array with the arguments [0,
0.2, , 1.8, 2].

>> x = 0:0.2:2

x =
Columns 1 through 7

0 0.2000 0.4000 0.6000 0.8000 1.0000 1.2000

Columns 8 through 11

1.4000 1.6000 1.8000 2.0000

For making the row of function values, we use array operations. Here, using dots is necessary,
since the function f(x) should be evaluated per element of x.

>> y = x.^3./(1+x.^2)

y =
Columns 1 through 7

0 0.0077 0.0552 0.1588 0.3122 0.5000 0.7082

Columns 8 through 11

Asst. Prof. Sachin Shrestha 18


0.9270 1.1506 1.3755 1.6000

In fact, this boils down to a component wise division of a row of numerators and a row of
denominators.

5.3 Relational array operations

Relational array operations are operations where arrays are compared elementwise.

For example, for the matrices

the command for finding out which elements in A are larger than corresponding elements in is
given by:

>> A > B

ans =
0 1 1
1 1 0

Entries with a ‘1’ (true) indicate the elements of A that are larger than corresponding elements
of B. Otherwise the entry will be ‘0’ (false). The result is thus an array with Boolean entries. You
can only compare the elements of array and if the arrays and have the same size,
or if one of the arrays is a scalar. For example,

>> A > 2

gives:

Asst. Prof. Sachin Shrestha 19


ans =
1 1 1
1 1 0

The relational operations are given in the Table 1.6.

Table 1.6: Relation operators

Operation Meaning
> greater than
>= greater than or equal to
< lower than
<= lower than or equal to
== equal to
~= not equal to

Relational operations are often used in combination with the function find. Look at the result of
the command help find.

5.4 Other array operations

In MATLAB, the mathematical standard functions sin, cos, sqrt, atan, asin, etc.
automatically operate on arrays.

>> a = [1 2 3];
>> sin(a)

ans =
0.8415 0.9093 0.1411

>> sqrt(a)

ans =
1.0000 1.4142 1.7321

Consider the function f(x) = x sin(x). A row of function values can be generated with the following
command:

Asst. Prof. Sachin Shrestha 20


>> x = 0:0.25:4*pi;
>> y = x.*sin(x)

The result is an array with the corresponding 51 function values.

Some other operations are

>> [nr,nc] = size(A)

The result gives the size of A , i.e., the number of rows nr and the number of columns nc. The
function

>> sum(A)

calculates the column sums in a rectangular array A and gives the sums in a row vector. (A column
sum is the sum of the elements of a column.) If A is a row vector, then the sum of the elements
of A is calculated. The function

>> prod(A)

does the same for the product.

5.5 Transposition

In an array (matrix), the rows and columns can be interchanged. This is called transposition. The
result is called the transposed array. In MATLAB, transposition can be performed with the
function transpose. After the commands

>> a = [1 2 3]

a =
1 2 3

>> A = [1 2;3 4;5 6]

A =
1 2
3 4
5 6

transposition proceeds as follows:

>> transpose(a)

Asst. Prof. Sachin Shrestha 21


ans =
1
2
3

and

>> transpose(A)

ans =
1 3 5
2 4 6

Transposition can also be performed by using an accent ('). The


commands transpose(A) and A' give the same result for arrays containing real valued elements,
but not for matrices having complex elements.

6 Graphs

To draw a graph, you first need to open a graphic screen. This is done with the command:

>> figure

Graphs are drawn with the command plot. The command

>> plot(v)

where is a row vector containing the numbers until , generates a plot where the points

(1, ), (2, ) until (n, ) are connected by straight lines. The command

>> plot(v,w)

with and two row vectors with the same number of elements, plots the points ( , ),
and connects them by straight lines. The command

>> plot(v,w,x,y)

plots the points ( , ) and ( , ) in the same figure.

Asst. Prof. Sachin Shrestha 22


To determine the appearance of your graph, after plotting a vector you can add the color and
linestyle of graph. For example, the command

>> plot(x,y,'r--')

will plot y versus x , with a red dashed line. Type help plot to see other line, marker and color
options.
Suppose that we want to draw the graph of the function on the
interval [0,2Π] consisting of 100 linearly spaced points.

Note that the smoothness of the graph is of course determined by the number of point. The graph
can be plotted by using the following commands:

>> x = 0:2*pi/99:2*pi;
>> y = (sin(x)+2*x)./(1+x.^2);
>> figure
>> plot(x,y)

When drawing a graph, the axes are chosen automatically. You can choose the lengths of the axes
yourself with

>> axis([XMIN XMAX YMIN YMAX])

which takes care that the graph is drawn in the rectangle XMIN ≤ x ≤ XMAX and

YMIN ≤ y ≤ YMAX.

After each new plot command, the old plot will in general disappear. If you want to draw different
plots with different plot commands in the same figure, you have to give the following command
after the first plot command

>> hold on

MATLAB then holds the graphs. The command

>> hold off

restores the state in which every new plot command makes the previous plot disappear.

Asst. Prof. Sachin Shrestha 23


The following commands are also important for handling the graphical screen.
You can make the graphical screen visible by either activating it, or by using the command

>> shg

The graphical screen remains the the same until either a new plot command is given or until it is
erased. The command for erasing the graphical screen is

>> clf

The command

>> grid

draws a grid in the graph.

>> title('title')

puts the title indicated by the string between the quotes above the plot. In the example above, the
title will be the word `title'.

>> text(x,y,'string')

puts the text `string' at the point (x,y) of the last plot.

>> xlabel('text')

writes information along the x-axis.

>> ylabel('text')

does the same for the y-axis.

6.1 Other graph types

You can use other plot functions in MATLAB as well. The most important are given in Figure 1.1.

Asst. Prof. Sachin Shrestha 24


Figure 1.1: Plot functions

 bar(x) produces a bar-plot of vector .


 plot3(x,y,z) produces a three-dimensional curve between the points, whose
coordinates are given in the vectors x , y , and z .
 mesh(X,Y,Z) produces a three-dimensional surface between the grid points, whose
coordinates are given in the matrices X , Y , and Z .
 contour(X,Y,Z) produces level curves in x,y plane, such that all points on a line have
the same value for z. Since the inputs in this functions are gridpoints, the inputs X , Y ,
and Z should be matrices.

You can save a figure by selecting "File \ Save as" and select the required file directory, filename
and file type.

Another option is to use the print command. Type help print for additional information. When
you want to be able to open and modify your figures again in MATLAB, you should save your
figure as a .fig file.

Asst. Prof. Sachin Shrestha 25


7 Script m-Files

If you have to execute a series of commands repeatedly, it might be better to write the commands
in a so called ‘script file’. The file should have a name with the extension ‘.m’.
As an example, let us consider the drawing of the function f(x) = |x sin(2Πx)| on the interval [0,2]
by using a ‘script file’: Through the menu ‘File \ New \ M-file’ the ‘MATLAB Editor/Debugger’
is opened. Type the following lines:

x = 0:0.1:2;
y = abs(x.*sin(2*pi*x));
plot(x,y)
title('f(x)= |x sin(2 pi x)| on the interval [0,2]')
xlabel('x')
ylabel('f(x)')
axis([0 2 0 2])
shg

Save the file through the menu ‘File \ Save’ under the name ‘picture.m’. If you now give the
command picture in MATLAB, then the graph of f(x) on the interval [0,2] will appear. Another

option to save and run a file written in your editor window is to press the button on top of it.
Be careful, that this will overwrite a possible previous file.

It is better to save the commands that generate a figure than to save the figure itself.

Asst. Prof. Sachin Shrestha 26


7 User defined functions

7.1 Function m-files

In MATLAB you can also define your own functions. MATLAB assumes by default that all
functions act on arrays. Therefore, you must keep in mind the rules for array operations when
writing your own functions. You can then combine your own functions with MATLAB functions.
A function definition has to be saved in a 'function file', which is a file with the extension `.m'. The
name of the file has to be the same as the name of the function, and should have the extension
`.m'.

Consider the function f(x) = x2 + ex. In MATLAB we will write a function with the same name.
The definition of the function has to be saved in the file ‘f.m’. Through the menu ‘File \ New \ M-
file’ or by typing edit on the command line, the ‘MATLAB Editor/Debugger’ is opened. If you
now type the lines:

function y = f(x)
y = x.^2 + exp(x);

and you save the file under the name ‘f.m’, then within MATLAB the function f(x) is available.
Some comments on the file above are in order.

 The first line of the file has to contain the word `function'. The variables used are local; they
will not be available in your 'Workspace'.
 If x is an array, then y becomes an array of function values.
 The semicolon at the end prevents that at every function evaluation unnecessary output
appears on your screen.

Always test the functions you have defined yourself!


You can change the definition of f(x) by typing the command edit f in the command prompt.
Warning: m-files should not be given the name of existing variables or MATLAB functions.
Conversely, after you have defined a function yourself, you should not give variables the same
name as your function, otherwise the function will not work any more (see Exercise 1.25).

Asst. Prof. Sachin Shrestha 27


7.2 Anonymous functions

Sometimes it is more convenient to define your function at the command line. MATLAB functions
produced at the command line are called anonymous functions. For example, consider again the
function f(x) = x2 + ex. We can create the anonymous function as follows:
>> f = @(x)(x.^2+exp(x))

Here, f is the name of the function, @ is the function handle, x is the input argument
and x.^2+exp(x) is the function.

Anonymous functions can have multiple input arguments. The general structure of anonymous
functions is name = @(input arguments) (functions).

The anonymous function will be evaluated in the same way as the function m-files. Thus the value
of f(1.2) will be obtained by the command

>> f(1.2)

ans =

4.7601

Asst. Prof. Sachin Shrestha 28


8 Saving and loading data

Very often, results of MATLAB calculations need to be reused elsewhere. The values of variables
can be saved in a `.mat file'. This can be done with the command

>> save filename

which results in all variables in use being saved in the file with the name `filename.mat'. The
extension ‘.mat’ does not necessary need to be given. If only a few variables need to be saved,
these variable should be specified after the file name, e.g. only the variables x and y are saved in
the file filename.mat with the command

>> save filename x y

A saved `.mat' file can be read into MATLAB with the command load

>> load filename

where the extension ‘.mat’ can be omitted. The saved variables and their values are stored in the
workspace and can now be used again.

Besides loading data stored in `.mat' files, MATLAB is useful for processing data which is
obtained from external sources, e.g., experimental measurements. Typically this data is available
as a plain text file organized into columns. MATLAB can easily handle tab or space-delimited
text.
There is more than one way to read data into MATLAB from an external data file. The simplest,
though least flexible, procedure is to use again the load command to read the entire content of the
file in a single step. The load command requires that the data in the file is organized into a
rectangular array. No column titles are permitted. One useful form of the load command is:

>> load measurements.txt

where ‘measurements.txt’ is the name of the file containing the data. The result of this operation
is that the data in `measurements.txt' is stored in a variable called `measurements'. Files with
various extension can be used. Note, that any extension except `.mat' indicates to MATLAB that

Asst. Prof. Sachin Shrestha 29


the data is stored as plain ASCII text. A ‘.mat’ extension is reserved for a file which has stored
MATLAB variables.

Suppose you had a simple ASCII file named `meas_xy.txt' that contained two columns of numbers.
The following MATLAB statements will load this data into the variable ‘meas_xy’, and then copy
it into two vectors, x and y .

>> load meas_xy.txt; % read data into the meas_xy variable


>> x = meas_xy(:,1); % copy first column of my_xy into x
>> y = meas_xy(:,2); % and second column into y

After applying these commands, the data stored in column 1 of the text file is stored in the
MATLAB variable x , and the data stored in column 2 of the text file is stored in the MATLAB
variable y. You are now able to process this data with MATLAB.

Another option to import data in MATLAB is to select "File \ Import Data". In the window
opening, you can select your data file. Selecting next in this window, various import options are
accessible. For example, you can choose whether MATLAB should split columns between spaces,
or between commas. Furthermore, you can choose the number of header rows. On the right hand
side of your window, you will see a preview how MATLAB will import the data. If you are
satisfied, select finish.

Asst. Prof. Sachin Shrestha 30


9 Exercises

Exercise 1.1: Entering commands

You are supposed to perform the following exercises in the specified order. Before entering each
of the commands, think about the output on the screen and the result of each exercise.

a)

>> a = 1+2+3+4+5+6

b)

>> b = 1+2+3+4+5+6;

c)

>> b+3

d)

>> 1+2+3+4+5+6

e)

>> c = 10*ans

Exercise 1.2: Interruption of calculations or output

Enter the array 0:900000 and make sure the output appears in the MATLAB Command Window.
Perform the exercise again and and use the key combination `ctrl-c' quickly. What is the effect?

Exercise 1.3: Incomplete commands

By entering a=[2,3,4] the array (2,3,4) is specified to the variable .

a) Enter >> a = [2,3,4 and use the `return' key. Finish the exercise.

Asst. Prof. Sachin Shrestha 31


b) Enter >> a = [2,3,4 and use the `return' key. Interrupt the input of the exercise.

Exercise 1.4: Removal of variables

Define the variables u=[2,3,4] and v=[1 5] and then delete them. Check if the variables are
actually deleted.

Exercise 1.5: Saving data files

Perform the following two exercises:

>> f = 2

and

>> g = 3 + f

Save the variables f and g in the file `try.mat'.

Close MATLAB and start it again. Load the file `try.mat' and see if the variables f and g are
known. Where is the file `try.mat' placed?

Delete the file `try.mat'.

Exercise 1.6

Make a row vector that consists of the fifth power of the first 40 natural numbers.

Exercise 1.7

In MATLAB calculate the product: .

Exercise 1.8

In MATLAB calculate the exact sum of:

Asst. Prof. Sachin Shrestha 32


Exercise 1.9

Draw a circle with radius 1 and center (0,0) in a square with -2 < x < 2 and -2 <y <2 . Make sure
that the circle looks round!

HINTS:
First make a list of x -coordinates and a list of y -coordinates. Draw the circle. Change the shape
of the figure by using the command >> axis in different combinations.

Asst. Prof. Sachin Shrestha 33

You might also like