22

MATLAB

An Introduction

By: Salim

Other resources used in the development of this document are:

-  “Learning MATLAB® 7” by the MathWorks

-  “Mastering MATLAB® 6 – A comprehensive Tutorial and Reference” by Duane Hanselman, Prentice Hall.

All students are HIGHLY encouraged to buy their own latest release of the Student Version of Matlab & Simulink found at: http://www.mathworks.com

Important:

SAVE ALL OF THE files asked for in the document. The instructor may ask at anytime to view some or all of the files and may ask the student to explain how these Matlab commands in those files work.

DO NOT PRINT the document. It is a long document.

Complete all items in this handout. Once each item is completed, check the box at the end of the corresponding item

Preface

The purpose of this document is to give the students an exposure to Matlab. Matlab is a powerful technical computing environment, therefore, many of its features will be taught as the need arises. Students are highly encouraged to go through the manuals provided with the student edition and to refer to the Matlab documentation. In addition, visit the Mathworks web site for additional information.

Again, the following information is geared towards – “getting started.”

What is Matlab?

“MATLAB is a high-level language and interactive environment that enables
one to perform computationally intensive tasks faster than with traditional programming languages such as C, C++, and Fortran.”

“You can use MATLAB in a wide range of applications, including signal and image processing, communications, control design, test and measurement, financial modeling and analysis, and computational biology. Add-on toolboxes (collections of special-purpose MATLAB functions, available separately) extend the MATLAB environment to solve particular classes of problems in these application areas.
MATLAB provides a number of features for documenting and sharing your work. You can integrate your MATLAB code with other languages and applications, and distribute your MATLAB algorithms and applications.

Key Features

  • -High-level language for technical computing
  • -Development environment for managing code, files, and data
  • -Interactive tools for iterative exploration, design, and problem solving
  • -Mathematical functions for linear algebra, statistics, Fourier analysis, filtering, optimization, and numerical integration
  • -2-D and 3-D graphics functions for visualizing data
  • -Tools for building custom graphical user interfaces
  • -Functions for integrating MATLAB based algorithms with external applications and languages, such as C, C++, Fortran, Java, COM, and Microsoft Excel “ Source: The Mathworks.com

All data in Matlab are stored as arrays, thus Matrices, vectors and arrays are, generally, the fundamental core of Matlab.

Features Explained in This Documents:

A-  Basic Features

  1. Mathematical operations – simple
  2. Matlab environment
  3. Variables
  4. Numeric data types
  5. Comments
  6. Standard math functions

B-  Matlab Path and files

  1. Managing files
  2. Hierarchy and Matlab search path
  3. M -files

C-  Arrays and Matrices

  1. Arrays indexing
  2. Array manipulations
  3. Array mathematics
  4. Sorting
  5. Factorization
  6. Appending, truncating, split, reverse, pad, etc.

D-  Character Strings

  1. String functions
  2. String to number, number to string
  3. String evaluation

E-  Operators

  1. Mathematical
  2. Relational
  3. Logical

F-  Control Flow

  1. For loop
  2. While loops
  3. Conditional
  4. Switch
  5. Try-catch

G-  Functions and function call

  1. Creating own functions
  2. Creating own toolbox
  3. Function evaluation

H-  Time functions

I-  Matrix Algebra

  1. Linear Equations
  2. Matrix functions
  3. Relation to LTI systems

J-  Data Analysis and Interpolation

  1. Data analysis
  2. Statistical functions
  3. 1-D and 2-D interpolation

K-  Polynomials

  1. Roots
  2. Operations

L-  Mathematics

  1. Linear and nonlinear differential equations
  2. Initial value problems
  3. Boundary value problems
  4. Integration
  5. Differentiation

M-  Graphics

  1. 1-D plots
  2. 1-D subplots / multiple plots
  3. 2-D plots
  4. 3-D plots (mesh, surface, contour plots)

N-  Data Files

O-  GUI

P-  Control Design Toolbox

Q-  Symbolic Toolbox


This document is written as an interactive discovery. Students will answer questions as they arise. Read all parts of this document – make sure you explore all items listed and beyond. Matlab is very powerful – This document basically just a getting started lesson.

A-  Basic Features

When you start Matlab, typically three windows appear. The Command Window, the Current Directory/Workspace, Command History. The workspace keeps the commands and values of variables. As well, the size of each variable is kept in the workspace. You can modify (add or remove) display windows by selection “desktop”>”desktop layout” and checking/un checking options.

Exercise -1

Stat Matlab

In the command window, at the prompt, type the following:

> a=5

>b=6

>c=12; (note : “ ;” was added here)

Notice how the inclusion of “;” suppresses printing.

> d=a+b+c;

>d

View the Workspace window for variables

At the command prompt, type the following:

who

> whos

What is the difference in result? ------

Check this box when this exercise is completed

Arithmetic operators:

The typical operators are used:

+, -, *, ^ and

/

\

In the Matlab command window, try the following:

> 12/5

> 12\5

>5/12

What does the symbol “\” do? ------

You may type help \ at the command prompt

The order of operations is consistent with the usual rules of operations.

Check this box when this exercise is completed

About Variables:

-  Variables are case sensitive

-  Variable names can contain up 31 characters (anything beyond is ignored)

-  Variable names must start with a letter followed by any number of letters, digits, or underscore.

-  Exceptions are Matlab reserved words such as: end, while, for, try, catch, switch, …

Special variables:

ans default variable name used for result

beep as the name implies

pi

inf infinity

NaN not a number

i or j

nargin number of input arguments in a function

nargout number of output arguments in a function

realmin smallest positive floating point number

realmax largest positive floating point number

in the command prompt, type the following

> help realmin

>help varargin

>help vararout

Check this box when this exercise is completed

Comments:

Comments are included by including the symbol “ % “

Type the following:

>a = 5; % this is a

>% the following is b

> b =20;

Notice the color coding

Complex Numbers

We can write complex numbers as:

a + bi or a+bj

Example:

Let us define two complex numbers and perform some simple mathematical operations:

Type the following

>x=4 – 5j;

>y=-2 + 8j;

find the following:

a)  x+y = ------

b)  x-y = ------

c)  x/y = ------

d)  magnitude of x = ------(what command did you use?) ------

e)  argument of x = ------(what command did you use?) ------

f)  complex conjugate of x = ------(what did you use?) ------

Check this box when this exercise is completed

Explore the following using help command: e.g., >help abs (it is important to remember and understand these features.)

abs

angle

float

double

single

isfloat

sint

uint

format

complex

cplxpair

conj

ceil

floor

fix

mod

rem

sqrt

gcd

lcm

etc……

-  type who at the prompt

-  clear one of the variables from the workspace (say a):

> clear a

who

notice , a is not in the list anymore

Clear all variables:

> clear all

>who (notice they are gone!)

Clear the command window screen

> clc

Now, let us do the following:

>a=10;

b=12;

>c=a+b;

d=c/12

Suppose we want to change the value of a, we then have to use the up and down cursers to get to a, but we then have to execute every command that uses it in order again.

Change a to 50 and determine d: d = ------(re-run every command that follows (specially those that are directly or indirectly dependent on the variable a.)

Now, you can easily go back to a as follows:

At the prompt, type a and hit the up arrow !!! notice quick access …

Check this box when this exercise is completed

Explore format:

>pi

format long

>pi

>format (sets back to default – same as format short)

>.>format short e

>pi

>help format

Explore this feature a bit.

>format rat

>pi

>format

MATLAB provides information about the computer in use and about MATLAB itself and all the toolboxes installed.

Try these commands:

>computer

>version (this is for MATLAB version)

>ver (this is about MATLAB and the toolboxes installed)

Check this box when this exercise is completed

B-  Path

MATLAB uses a search path to find information stored in files in numerous directories and subdirectories.. To list all the directories where the MATLAB files are found type the command:

>matlabpath

or

>path

Important:

Use of MATLAB search is described by the following:

When you enter a command (assume hello) at the prompt ( a command to run an instruction , or a command to execute a file name, ... or whatever) MATLAB does the following:

a-  It checks to see if hello is a variable in the MATLAB workspace

b-  it checks to see if hello is a built in function

c-  it checks if a filename hello.m exists in the current directory.

d-  it checks to see if hello exists anywhere in the MATLAB search path

e-  if not found, an error is reported.

NEVER alter any of the MATLAB files. All of your work MUST be done in a separate directory. You can always access and call the different Matlab functions … NEVER alter them .

Create a folder on the N drive and call it MLWORK

Add this folder to the MATLAB search path. To do this, follow these instructions:

-  in the MATLAB command window, go to file /set path/ add folder

-  follow the instructions on the screen (do not forget to click save on the add path window.)

Check this box when this exercise is completed

Script M-Files

As the number of commands increase, it becomes tedious to input the commands at the Matlab command window. The solution is made easy with Matlab: create a text files and enter your Matlab commands in it (MATLAB program file.) Save the file as a .m file, e.g. hello.m (This step is explained in the following practice exercise.)

First, make sure the folder creation step above is completed! \

-  In the Matlab desktop, select: file>new>m-file

-  Type the following code

% This is program number -1

% getting to know m-files

a=10;b=20;c=30;

%

x=2;

% let the value of y be user input

% the following statement is echoed to the screen

disp(' Please enter a number for y') %notice I did not use “;” why?

y=input('the value of y = ')

disp(' ------')

disp(' The result is')

disp(' hit any key to continue')

pause%

W=a+b+c/x+y

Select file>save as> (navigate to MLWORK directory) and type the file name hello.m

Check this box when this exercise is completed

(You can run /debug from the editor window, however for now, go to the Matlab command window and at the prompt, type the file name:

>hello

notice how the file runs … now, it is easy to modify and run again …

explore pause , pause(5) , etc .. in the hello.m program.

In the command window, do the following:

>echo on

>hello

What do you notice ?

> echo off

>hello

>help keyboard

>help return

What do these two commands do? (useful for debugging)

Check this box when this exercise is completed

C-  Arrays and Matrices

Recall, arrays and matrices are the core of Matlab --- thus we need to explore/ discover some of the features … This topic will be dealt with in greater details throughout the course.

[ ] are used for arrays and matrices…

the 1-D row array x can be entered as:

>x=[1,2,4,5]

or

>x=[1 2 4 5] This is the form I personally prefer to use …

>y=[1;2;4;5] this defines a Column vector notice the use of ;

Check this box when this exercise is completed

Let us write a .m file to explore some of the array operations:

In Matlab command window, file>new file>m-file

Type the following:

clear all

echo on

% on 1-D arrays

% let us suppose we have the following:

% x = { 1,4,6,10,20} and

% y = 20*x+5

% then

x=[1 4 6 10 20]; % this is how the array is entered

y=20*x+5;

file>save as> hello2.m

Now, in the Matlab command window do the following:

>hello2

>x

>y

>size(x)

>length(y)

What does the result of size mean? ------

What does the result of length mean? ------

Check this box when this exercise is completed

>g=x’;

>g

What is the dimension of g? ------

What is the mathematical meaning of ‘ in g=x’ ? ------

We can index elements:

>x(3)

We can modify elements of an array:

>y

>y(2)=1000;

>y

We can list a range of elements:

>x(2:4)

What does the above do? ------

>x(3:-1:1)

What does the above do? ------

>x(2:2:5)

What does the above do?

>x(3:end)

>y

>y(5)

>y([2 4 5])

What does the above do ? ------

>[y(2) y(4) y(5)] %The previous one is simpler !!!

Check this box when this exercise is completed

Array Construction

Enter and explore the following:

Create a new .m file and type the following:

% More on 1-D arrays ... Array manipulations

clear all

clc

echo off

x=0:.2:2;

y=sin(x);

disp(' the 1-D arrays are: ')

x

y

pause %

disp('size of x and y vectors are:')

size(x)

size(y)

pause

disp('let us change the orientation of array y and place the new vector in z')

z=y' % this is the transpose command.

disp(' size of vector z is:')

size(z)

pause

disp('let us append vector x by 3 values, two more in the beginning and one at the end')

disp('the original x is:')

x

pause

disp('now the new x is:')

x=[-2 -1 x 3]; %handy to know

x

disp('the size of this x is:')

size(x)

pause

disp('let us change x back')

% the following use of : is handy to know

x=x(:,3:end-1) % isn't this fun or what FYI: The first : indicates ALL rows ....

pause

save the file in the MLWORK folder as: hello3.m