0% found this document useful (0 votes)
4 views

Part02 Matlab Fundamentals

This document provides an introduction to MATLAB fundamentals, covering the MATLAB environment, command window, and basic operations with matrices and variables. It explains how to navigate the MATLAB desktop, utilize the toolstrip, and execute commands, along with details on saving workspaces and changing preferences. Additionally, it discusses mathematical operators, functions, and the creation of vectors and matrices, including examples and commands for effective usage.

Uploaded by

Thobius Joseph
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Part02 Matlab Fundamentals

This document provides an introduction to MATLAB fundamentals, covering the MATLAB environment, command window, and basic operations with matrices and variables. It explains how to navigate the MATLAB desktop, utilize the toolstrip, and execute commands, along with details on saving workspaces and changing preferences. Additionally, it discusses mathematical operators, functions, and the creation of vectors and matrices, including examples and commands for effective usage.

Uploaded by

Thobius Joseph
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 66

ES171 Unit 4 Part 2

MATLAB FUNDAMENTALS
What to be covered in this
part?
• Introduction to MATLAB
Environment
• Matrices, Polynomials,
Introduction to M-files (scripts),
statistical functions, etc
Operating Environment
• Starting Matlab:
 Start > All Programs > Matlab > R2015b
 Start > Matlab R2015b (if pinned there)
 Can also create a shortcut on the desktop
• Matlab Desktop:
 Title bar (displays Matlab version), Menus,
toolbar and some windows are displayed.
 Possible windows are: Command window,
Current folder, Command history and
workspace
 Maximize the Matlab desktop for better view
 Windows can be closed and re-opened.
 desktop > desktop layout > default to view
default windows
The Matlab Desktop

Current Folder

Workspace
Command window

Command History
The Toolstrip

• The Toolstrip organizes MATLAB


functionality in a series of tabs.
• Tabs are divided into sections that contain
a series of related controls.
• The controls are buttons, drop-down
menus and other user interface elements
that you use to do things in MATLAB.
• The light blue bar in the upper right corner
is called the Quick Access Toolbar.
The Toolstrip-Global Tabs

• When you open R2015b for the first time,


you will notice three tabs -- the Home tab,
the Plots tab, and the Apps tab.
• These three tabs are always there no
matter what you are doing in MATLAB. For
that reason, they are called global tabs.
• The Home tab, shown above, is where you
go to do general purpose operations like
creating new files, importing data,
managing your workspace, and setting
The Toolstrip-Global Tabs

• The Plots tab, shown above, is where you


go to create MATLAB Plots.
• The Plots tab displays a gallery of plots
available in MATLAB and any toolboxes
that you have installed.
• We will study these plots in when we do
Matlab graphing.
The Toolstrip-Global Tabs

• The last of the global tabs is the Apps tab,


shown above.
• It is the place you go to run interactive
MATLAB applications.
• Some of those applications come from
MathWorks -- you get them automatically
with Toolboxes that you have installed.
• The Apps tab presents a gallery of apps
that you have installed.
The Toolstrip-Contextual Tabs

• In addition to global tabs, the Toolstrip also has


contexual tabs.
• Contextual tabs only appear when you're doing
certain things in MATLAB.
• Let's look at the Editor as an example. When you
edit a file, three new tabs appear -- the Editor
tab, Publish tab, and View tab.
• If the Editor is docked in the Desktop, those tabs
related to the Editor appear next to the global
tabs as shown above.
Windows
• Command window – where you enter commands,
variables and run functions (details given shortly)
• Command history: Commands you enter in the
Command Window are logged in the Command
History window (Details given shortly)
• Current folder: Shows contents of current folder.
Can be changed by typing the path of the folder
you want to be the current folder. Current folder
dropdown is also shown beside the toolbar. Click
browse for folder( …) to change it.
• Workspace: Shows variables in memory
Command Window
• Commands are typed after the MATLAB
prompt: >>
• Commands are entered with the
RETURN key.
• Commands are case sensitive.
• To interrupt a task, press Ctrl+C
• The output is suppressed by ending the
command with a semicolon (;).
Some few commands
• clc: clears command input window. Also type
home
• version: Displays MATLAB version only. This
can also be seen in the title bar of Matlab
desktop or use Help > About Matlab.
• ver: Displays version of matlab installed and
other toolboxes and their versions
• pwd – displays the current folder/directory.
(Also cd)
• more on/off – toggles the ability to control
paged output in the command window. Press
spacebar to display next page
Quitting Matlab
Use one of the following methods:
• Type exit or quit at Command window
• Use File > Exit MATLAB
• Press Ctrl + Q
• Click Close (x) on top right corner of
MATLAB Title bar
Extra on commands – Recalling
commands:
• UP and DOWN arrow keys on the
keyboard to recall previous commands
• Type the first few characters of previous
command and press the UP arrow key !!
Command History Window
• To re-execute a command:
 double click the line containing the
command in the command history
window
 drag and drop the command, or
 copy it from the command history and
paste it in the command window.
• To clear the command history, right click in
the command history window and select
Clear Command History. Or Home>code >
clear commands>command history
• Select commands and right-click in the
command history to get more options
Workspace
• Consists of the set of variables built up during a
MATLAB session and stored in memory.
• To edit a variable, double click the variable in
workspace and variable editor will be opened
containing array elements of that variable.
• To save the whole workspace:
Home>Variable>Save Workspace. Filename
extension will be .mat. Can also use save on the
quick access toolbar. Retrieve:
Home>Variable>> import data..
• To save few variables, select (Ctrl, Shift) and
then right click and choose Save As..
• Select variables and right-click to get more
options (delete, duplicate).
• You can also create a new variable in the
Changing Preferences
Home>Environment >Preferences… to change
some settings on the desktop
Examples:
• Font > Custom : to change the font types and
sizes
• Command window > Display
 Show getting started message bar
 Show function Browser button
• Command History > Saving
 Save after .. commands – this will save
commands history
• Current folder
 Most recent directories to save
Getting help
• Help Browser
 click the help button (?) on the toolbar
 Help > Product help from the menu
 Type doc or helpdesk or Helpbrowser at
command window
• Typing help produces a listing of all help topics
in the command window.
 For explanation of each help topic, type
helpwin
 For details of a specific command or
function or topic use help
<commandname> or doc
<commandname> or doc <topicname>
 doc <commandname> gives details
Matlab Demos/Examples
• To get examples/demos:
 Help > demos
 Type demo at command window
 Helpbrowser and for each toolbox expand to
get Demos
• Run the Matlab getting started using:
help > demos > MATLAB > demos >
Getting started.
• Note: Some videos might require
internet connection. Also requires
Adobe Flash Player
• Most videos will run in the default
browser
Predefined Values
• Powers of 10 is represented using e or E.
Example: 1.45x103 use 1.45e3; 1.45x10-3 use
1.45e-3
• Predefined values:
 pi (value of )
 i or j (sqrt(-1))
 inf : (∞) - Result of division by 0
 NaN or nan (Not a number) – indeterminate
forms such as 0/0
Mathematical Operators & Functions
• use help ops or doc ops (operators and
special characters)
 *, /, +, - , ^ (power), e (10 raised to power –
example: 1.45x103 use 1.45e3)
• Example: (2+3)/45; cos(pi); sin(pi/4)
• Remember precedence of operators (BODMAS)
• ans is a default variable name if no
assignment
• help elfun or doc elfun to get help on
elementary functions (trigonometric,
exponential, complex, rounding and remainder
functions, etc).
• Arguments for trigonometric functions should
be radians, except for functions such as sind,
Mathematical Operators & Functions
• doc elfun – elementary functions
• doc specfun – specialized functions
(factorial, lcm, gcd, etc)
• Some functions:
 sqrt(x), abs(x), exp(x), log(x)  ln(x);
log10(x)log10(x), rem(x,y) – remainder
when x is divided by y, nthroot (x,N)
 sin(x), cos(x), tan(x), asin(x), acos(x),
atan(x) etc where x is in radians.
 sind(x), cosd(x), tand(x) where x is in
degrees
 max(x), min(x), std(x) – statistical functions
 round(x), ceil(x), floor(x),
Variables (1)
• Use assignment operator to create a variable
• a=5, b=a+7 , x=tan(pi/4), a=a+7
• Results are assigned to variables specified and
displayed
• semicolon suppresses display. e.g. y=34;
• To display the value assigned to a variable,
simply type the name of the variable.
• Created variables are seen in workspace
window
• Several variables can be created or displayed
on a single line; separate them using commas
or semicolons.
• If you type a nonexistent variable, an error is
displayed: Undefined function or variable…
Variables (2)
Variable names:
• Are case sensitive
• must be a single word containing no space
• must begin with a letter, followed by any
number of letters (small and capital), digits (0-
9), or underscores (_)
• can contain up to 63 characters (use
namelengthmax)
• cannot be reserved words (type iskeyword to
see reserved words)
• never use built-in function names or command
names as variable names. If you do, clear the
variable name using clear <varname>.
• ans is a default variable name if no assignment
Variables (3)
• Use names that reflect the values they
represent (VERY IMPORTANT FOR EVERY
PROGRAMMER)
• who and whos commands displays available
variables in the memory. whos gives the
dimensions of variables
• clear clears all the variables from memory.
Individual variables can be cleared by
specifying variables names separated by
spaces (not commas).
Example: clear x b y
• Can also clear variables from workspace
window
Numbers
• All numbers are stored internally using
the long format specified by the IEEE
floating-point standard.
• Floating-point numbers have a finite
precision of roughly 16 significant
decimal digits and a finite range of
roughly 10-308 to 10+308
Format command
• Integer 999999999 (9 9’s) will be displayed as
you have typed it i.e. an integer up to 9 digits
• For more than 9 digits, it will be displayed in
scientific notation with five significant digits.
Example: 1234567890 will be displayed as
1.2346e+009
• Numbers with decimal parts are displayed
with 4 significant digits. If the value of x is in
the range 0.001<x≤1000.0 it is displayed in
fixed point form otherwise scientific (floating
point) is used in which case the mantissa is
between 1 and 9.9999. e.g. 1000.1 will be
displayed as 1.0001e+003, but 999.99 will be
displayed as 999.9900
Changing Display Format
• Use format command. doc format for help
• Syntax: format display_format
• Possible formats:
 short (default), long, shortE, longE, shortG,
longG, shortEng, longEng.
 Hex, bank, +, rat (Ratio of small integers.
For example, 355/113)
• Note: Format command does not change
internal representation of a number
• format compact suppresses many of the
blank lines that appear in the output
• format loose removes format compact mode
Changing Display Format
• To get the current format: get(0,’format’)
Default: format short
• For the spacing: get(0,’formatspacing’)
• To return to default format, type format
followed by ENTER key.

• Exercise: display value of pi for different


formats
Complex Numbers
• sqrt(-1) => i or j
• x=2+2i or 2+2j or 2+2*i or x=2+2*sqrt(-
1)
• x=2+sin(0.5)*j or x=2+j*sin(0.5)
• Termination with i or j works with numbers, not
expressions.
• For expressions, use *i or *j, e.g.
x=5+sin(0.5)*j
• Operations on complex numbers generally
lead to complex numbers.
• The functions real and imag can be used to
extract the real and imaginary parts
respectively.
• Other functions: abs, angle, conj (complex
Vectors and Matrices
Row Vectors
• Row vectors are entered using square
brackets where elements are separated by
comma or space. For readability, use
spaces. Examples:
x=[1 2 3];
• Several vectors can be created on a single line
by separating them using comma or
semicolon. Semicolon suppresses displaying
them. Example: y=[3 4 56 23];z= [6 7
2+5i]
Note: Mathematical functions or expressions can
be used to define elements of a vector:
Example: A= [sqrt(5) cos(2/3*pi)]
Column Vectors
• Column vectors are entered using square
brackets where elements are separated by
semicolon Example:
x=[1 ;2; 3];
• Transposing column vectors can be obtained
by a row vector and vice versa. Apostrophe
symbol (') is used for transpose.
Example:
row_vector=[1 2 3 4]
column_vector= row_vector'
Matrices
• To create an m-by-n matrix (m rows and
n columns),separate the row elements
using spaces and separate the rows
using semicolons. Example:
A = [1 2 3 4; 5 6 7 8; 9 10 11 12];
• Pressing ENTER key tells MATLAB to
start a new row: i.e.
g=[1 2 3
5 6 7]
• All rows should contain the same
number of columns.
Scale factor
With fornat short and format long, a common
scale factor is applied to the whole vector if
its elements are very large, very small or
differ greatly in magnitude.
e.g. format short; x=[1e3 1 1e-4]
Results into:
1.0e+003 *[1.0000 0.0010 0.0000]
Note the third element is 1e-7 which is
represented by by 0.0000 in short
format!! Use format long to see actual
values in 0.0000!!
To avoid a scaling factor, try format bank
or format shortE. Using format shortE we
get:
x= 1.0000e+03 1.0000e+00 1.0000e-
linspace
• The linspace function generates linearly
spaced vectors. Syntax:
t=linspace(a,b);
t=linspace(a,b,n)
linspace creates a row vector linearly spaced
from a to b with length n (number of points n is
optional; its default value is 100). Example:
t1=linspace(1,10); % creates 100 points from 1
to 10.
t2=linspace(1,10,20); % creates 20 points from 1
to 10.

linspace creates row vector. To get column


vectors, use transpose. Example
Array indexing (1)
• For row or column vector, use:
array_name(index)
Example: x=[23 -1 4 0 25 6];
Then: x(1)=23, x(2)=-1; x(5)=25, etc
Note: x(end) gives the last element
• For matrix, use: matrix_name(row,column)
Example: A=[1 2 3; 6 9 10; 45 67 -1]; Then
A(1,2) gives 2, A(3,2) gives 67, etc
• If only one index is used, then MATLAB find the
index by counting elements down the column
starting with the first column. For example:
A(5) gives the value of 9
Note: Using indexing technique, a new value of
element in a a vector or matrix can be
changed. For example: x(2)=34 changes
second element to 34. Index must be in the
range!
Array indexing (2)

• size(A) gives the dimension of matrix A (rows and


columns
• size(A,1) gives the number of rows, and size(A,2)
gives the number of columns. [rows columns]=size(A)
Colon operator (1)
• Get help on this operator using doc colon
• Colon (:) can be used to construct a vector.
• Syntax:
vectorname=[firstvalue:increment:lastva
lue] Increment can be +ve or –ve.. If
increment is not specified, then default
increment become 1.
• For example: x=[1:1:10] and x=[1:10]creates
a row vector with elements: 1 2 3 …10. More
examples:
m=[1:3:19];
y=[0:0.1:23]; % brackets can be
removed
z=[-1.2:0.2:20];
Colon operator (2)
Question: Create a vector x which
contains angles (in degrees) 0, 2, 4, 6, …
20. Using x, create another vector y which
contains sin(x)
Solution:
x=0:2:20; y=sin(x*pi/180);%use
radians
or
x=0:2:20; y=sind(x); % use degrees
Colon operator (3)
• Colon operator can be used for indexing
x=[12 24 32 45 5 65 7 88 99 100];
x(1:4) % x(1), x(2), x(3), x(4) equivalent to
x(1:1:4)
x(3:end) % x(3), x(4), …, last element
x(1:2:5) % x(1), x(3), x(5) increment index by 2
x(3:-1:1) % x(3), x(2), x(1)
x(3:1) % empty matrix
Note1: To pick index randomly, enclose indices
in []. For example, to extract index 4 then 5 then
1 use:
x([4 5 1]). Error results if [] are omitted!
Transpose operator has higher precedence compared to
colon.
Colon operator (4) -advanced
• A(:) is all the elements of A, regarded as a
single column (column vector) starting with
the first column
• A(:,J) gives the J-th column of A (column J in
all rows). A(J,:) – gives the J-th row for all
columns
• A(J:K) gives [A(J),A(J+1),...,A(K)] – counts
columnwise for r x c matrix. Results in a row
vector
• A(:,J:K) gives [A(:,J),A(:,J+1),...,A(:,K)] and so
on (all rows, but use column j up to K)
• Questions: What does the following represent?
A(J:K,:)
A(M:N,Q:P) Extra: A(:,[f g h]) => columns f,g
Colon operator (5)
Deleting Rows and Columns
A=[5 7 8 2 10 6]
A(2)=[] % this results A to be [5 8 2 10 6]

B=[4 5 7
7 8 9
12 34 56];
C=B;
C(:,2)=[] % deletes the second column of C

B(3,:)=[] % deletes the third row of B


Standard arrays
 length(x) returns the length of vector x. It is
equiv. to max(size(x)) for non-empty arrays
and 0 for empty ones
 eye(n) – creates nxn identity matrix
 ones(r,c) – creates rxc matrix whose all
elements are equal to 1. If c is omitted then
c=r is assumed!. Ones(r,r) creates square
matrix
 zeros(r,c) – creates rxc matrix whose all
elements are equal to zero. If c is omitted then
c=r is assumed!!!
 rand(r,c) creates rxc uniform distributed matrix
with random entries on the interval (0.0,1.0). If
c is omitted, we get rxr matrix
 diag(x) – places elements of array x on the
main diagonal if x is a column/row vector
 Magic(n) – nxn matrix. What are the
properties if n>=3?  Magic
MATLAB Editor Basics
(script m-files)
Matlab Editor (1)
• (1) Use Home>File> New > script to start
Matlab editor
• (2) Use edit <filename> from command
window. MATLAB will automatically add
extension .m.
• (3) Press Ctrl+N from the command window to
open the editor.

• Save file with .m extension in Matlab’s path


(e.g. in current folder)
• Within the editor you can save, open existing
m-file or create a new file.
• Get help within the editor use: Help > Using
the M-file editor option
Matlab Editor (2)
Example: part02ex00.m
clc % clear the command window
clear % clear all variable in the
workspace
a=-2; b=3; c=4;
% semicolons suppresses display
% no semicolon at the end of x1 and x2
% in order to display the values of x1
and x2
x1=(-b+sqrt(b^2-4*a*c))/(2*a)
x2=(-b-sqrt(b^2-4*a*c))/(2*a)
Matlab Editor (3)
• To execute commands in m-file:
(1) Type m-file name (without extension) at
command prompt.
(2) To run from within editor, use Debug > save
file and Run or F5 or save file and Run on
the toolbar. Results appears in the command
window.
(3) Right-click the file and choose run from the
current folder.
• All scripts share the same workspace.
 Scripts can make use of existing variables in
the workspace.
 Results are left in the workspace.
 Variables in the workspace are affected each
time another script is run.
Errors in executing m-file
• File must have extension .m in order to
run! If NOT, the run is disabled in the
debug menu and also run on the toolbar
is disabled
 Demo in the class for files with no extension
.m
• Matlab acts as an interpreter and not a
compiler!
 If there is an error, Matlab stops

execution and displays an error


message in the command window. Click
on the error line (on the link) to go
straight to that line number in the editor
Extra – Matlab editor (1)
 Normally, the commands read in from the m-
file are not displayed as they are evaluated.
The echo on command tells MATLAB to
display or echo commands to the command
window as they are read and executed. Echo
off turns off this mode
 Use File > Print… to print m-file
• Commenting a block: select and use
Text > Comment
• Save as from File menu
• Open most recently used files from File
menu
• File Tabs if you open more that one file
Extra – Matlab editor (2)
• Change settings: Home>Environment >
Preferences > Editor/Debugger
 Display: Highlight current line
 Show line numbers
 Autosave: Enable autosave in the
MATLAB Editor
• Save every … minutes (5 minutes is
default)
• Automatically delete autosave files
• Replace extension with .asv
 To change font for different windows

including the editor, use:


Home>Environment> Preferences > Fonts
Array Arithmetic (1)
• Addition, subtraction, multiplication and
division by a scalar simply applies the
operation to all elements of the array
Example: g=[1 2 3 4; 5 6 7 8; 9 10 11 12];
g-2, 2*g-1, 2*g/5 +1 part2ex01.m
• Arrays addition (+), array subtraction (-), array
multiplication (.*), right array division (./), left
array division (.\) and array exponential (.^)
are performed element by element. Arrays
must have the same dimensions (rows and
columns). For help use doc arith.
Example part2ex02.m
• =[1 2; 3 4], b=[5 6; 6 8],
• a+b, a-b, a.*b, a./b , a.\b, a.^b
Array Arithmetic (2)
• Multiplying two matrices: Rule of thumb is :
number of columns of first matrix must be
equal to number of rows of second matrix.
• If A=rA x cA AND B=rB x cB then for A*B to be
defined, then cA=rB and dimension of the
product will be: rA x cB (r is for rows, c is for
columns)
• Division of two matrices: A\B  A-1B (this is
called left division).
• Determinant of square matrix: use
det(matrix) function
• Inverse of square matrix: inv function exists
for finding inverse of matrix. inv(A) exists if A
is a square matrix and its determinant is not
equal to zero!!!
Solving Simultaneous Equations

Ax B  x  A 1B %(inv(A) * B)
part2ex04A.m
 x  y  2 z 2 A = [-1 1 2; 3 -1 1;-1
3 4];
3x  y  z 6 B = [2;6;4];
 x  3 y  4 z 4 x = A\B
% x=x(1)=1;
y=x(2)=-1; z=x(3)=2
  1 1 2  x   2
    
 3  1 1   y   6  part2ex04B.m
  1 3 4  z   4 compares time
     taken for inv(A)*B
and A\B using tic
and toc
Statistical Functions
• Functions: min, max, mean, median, std,
sum, prod, cumsum, cumprod. Example for
vectors: part2ex06.m
• For matrices, they operate columnwise.
Example for matrices: part2ex07.m
• When used with two output arguments, min
and max columns, they return also the
corresponding index (or location) of the min or
max value respectively.
[minval,indices] = min(X) % min value
and indices are returned
• minvalue=min(X) % only min. value is
returned
Example part2ex08.m Extra: mean(x,1) –
column;mean(x,2)-row
Sorting
• For vectors, sort(x) sorts the elements of x in
ascending order. Refer to part2ex09.m
• For matrices, sort(x) sorts each column of x in
ascending order. Refer to part2ex10.m
• sort(x,1)  sort(x) - sorts columnwise
• sort(x,2) sorts rowwise. Refer to part2ex11.m
• sort(x,'ascend') =>ascending order,
sort(x,‘descend') =>descending order. Check if
Matlab version you use supports this. R2010B
support it. Extra: sort(x,1,’descend’)
• sortrows(A) sort rows in ascending order using the
first Column. A must be either a matrix or a column
vector.
• sortrows(A, column) performs sorting the way Excel
performs sorting. Default is ascending. For
Arithmetic, Relational and Logical
Operators
• Used by find function
• Arithmetic: + - ./ .* .\ .^ ^ : .’ ’ * /
• Relational: <, <=, >, >=, ==, ~= (not equal)
• Logical operators: & , ¦ and ~
• For precedence, refer to full Matlab lecture
notes (posted to students).
• Extra: Also you can get precedence using: help
precedence at the command window.
find function (1) – Very Powerful
• indices = find(x) returns the indices of the
array x that point to nonzero elements. If none
is found, find returns an empty matrix. It is
equivalent to indices=find(x~=0)
x = [1 0 4 -3 0 0 0 8 6];
indices = find(x)
returns linear indices for the nonzero entries of x.
• indices = 1 3 4 8 9
• To get elements, use: x(indices). This will
return:
1 4 -3 8 6
• find(x) regards x as x(:), which is the long
column vector formed by concatenating the
columns of x.
find function (2)
• [r,c] = find(x) returns the row and column
indices of the nonzero entries in the matrix x.
Example:
z=[8 0 6; 3 5 7; 4 9 0];
[r,c]=find(z)
[r,c] % this shows actual row and column
combination
Note: x(find(x)
Output:
 x(find(x~=0))
1 1
2 1
3 1 To find elements which are
2 2 positive use: x(find(x>0))
3 2
1 3
find function (3)
• can combine logical and relational operators
with find function
x = [-3 11 0 33 0 55];
x(find( x>0 & x < 10*pi)) % do not use
&&, it will result into errors
• This gives values which are greater than 0 but
less than 10. Qtn: How many elements?
• To determine how many elements meets
certain criteria, combine the length function
and find function. Example:
length(find(condition))
• Example: part2ex12.m demonstrates how you
can summarize test scores, as shown in the
next slide.
Find function (4)
marks=[23 45 99 67 56 43 21 67 89 100
35];
format compact
A_grade=length(find(marks>=70))
B_plus_grade=length(find(marks>=60 &
marks<70))
B_grade=length(find(marks>=50 &
marks<60))
C_grade=length(find(marks>=40 &
marks<50))
D_grade=length(find(marks>=35 &
marks<40))
E_grade=length(find(marks>=0 & marks<35))
Polynomials (1)
• Represented as vectors containing the
polynomial coefficients in descending order
p ( x) an x n  an  1 x n  1  an  2 x n  2  a1 x  a0
Example: p(x)=x3+5x2-3x+6  p=[1 5 -3 6];
• The roots function finds roots of polynomials
x3+5x2-3x+6=0  p=[1 5 -3 6]; roots(p)
Important: If some coefficients are missing, they
must be replaced by zeros !!!
** Can be used to solve quadratic equation!
• The poly function is used to form a polynomial
from its roots. It returns the coefficients of the
polynomial as a row vector. Example:
p2=poly([-1 -2]) returns p2= 1 3 2
Polynomials (2)
• Polyval function evaluates a polynomial at a
point. Syntax is:
polyval(polynomial,point)
• Polynomials are multiplied and divided using
the conv and deconv commands respectively
• C = conv(A, B) multiplies two polynomials
part2ex13.m demonstrates how you can
multiply two polynomials p(s)*q(s) given by
p(s)=s3+2s2+3s+4 and q(s)= s4+3s2-4s
Results: [1 2 6 6 1 0 -16 0]
• [Q,R] = deconv(B,A) deconvolves vector A out
of vector B (i.e. B/A) The result is returned in
vector Q and the remainder in vector R such
that
B = conv(A,Q) + R
demonstrates the value of q(s)/p(s) given above
[Q,R]=deconv([1 0 3 -4 0],[1 2 3 4])
Derivatives and Integrals of
Polynomials
• For derivative, use polyder function
• For integrals, use polyint function
• Use doc polyder and doc polyint for examples
and more details. Examples:
p=[2 4 -5 6]; der=polyder(p)  der = 6 8 -5
intg=polyint(p)
 intg =0.5000 1.3333 -2.5000 6.0000 0
k = polyder(a,b) returns the derivative of the
product of the polynomials a and b =>
polyder(conv(a,b))
[num,den] = polyder(b,a) returns the numerator
num and denominator den of the derivative of
the polynomial quotient b/a. demo:
d/dx((2x+3)/4x) 7.6

3 2
Homework: Write a series (2of  4 x  5statements
x Matlab x  6)dx to
 1.5
find the value of:
Importing data from Excel and text files
• Importing from Excel or text file, Go to:
Home>Variable> import Data…
• In the resulting dialog box, select .xls file
• Specify the range to import. You can drag and
select.
• Demo: using Import_Excel_data.xls
• Can also generate code for importing data
• Importing from text file:
• Demo: import_text_data.txt file
More on Importing data from text files
Use load filename.txt
• Reads content of file in single step and stores
in variable called <filename>.
• MATLAB can handle tab or space-delimited
text.
• Requires data in file to be organised into
rectangular array. No column titles.
• There should be an equal number of elements
in each row. One row per line.
• For help on import data: Matlab help >
Matlab > user's Guide > Data import and
Export > Import data > Import
Spreadsheets/Import Text Data Files
== END ==

You might also like