Matlab Primer
Matlab Primer
Matlab is a programming language and also provides software environment for using the language effectively.
Starting Matlab
Double click on the MATLAB icon ----( This starts the Matlab Desktop
The Desktop manages the Command Window
Depending upon how the default is set up, you might see 2 additional windows, namely Command History and Launch Pad Windows to the left.
Command Window is used to communicate with the Matlab program.
Matlab displays the prompt “ >> “ or ‘EDU>>’ for student Edition.
It indicates that Matlab is ready to receive instructions.
Matlab as a Calculator
>> 4+6=
ans=
10
>>4*25+6*20+8*10=
ans=
300
Basic Operations:
A+B Addition
A-B Subtraction
A*B Multiplication
A/B Right division
A\B Left division
A^B Exponentiation
These operations follow set of rules called Precedence
All mathematical statements are evaluated starting from left to right. Exponentiation is performed first having the highest precedence. This followed by multiplication and division with equal precedence, followed by addition and subtraction with equal precedence.
Where Parentheses appear, evaluation begins with innermost pair and proceeds outwards.
Examples:
Make note how precedence and parentheses change answers.
>>7+4*6
ans=
31
>>7+(4*6)
ans=
31
>>(7+4)*6
ans=
66
>> 5^2-10+8/4*2
ans=
16
>> 5^2-10+8/(4*2)
ans=
16
>>4*3^2-7
ans=
29
>>4*(3^2)-7
ans=
29
>>(4*3)^2-7
ans=
137
Remark Use parentheses to avoid any confusion with precedence.
Function and Variables
Functions and Variable names must begin with a letter and must contain less than 32 characters. The rest of the name can contain digits, letters and underscore
Characters.
Matlab is case sensitive. For example a name of a variable A12w is different from a12w or a12W or A12W. So one of them is defined and by mistake you try to use the other, Matlab will give you an error message.
Example
4 erasers, 6 pads, and 2 discs
Cost 25; 52; and 99 cents
>>erasers=4
erasers=
4
>>pads=6
pads=
6
>>discs=2
discs=
2
>>items=erasers+pads+discs
items=
12
>>cost=erasers*25+pads*52+discs*99
cost=
610
Remarks
(a) Escape, horizontal and vertical arrow, Backspace, delete, end commands perform the commonly assigned tasks
(b) Semicolon at the end of each statement will suppress printing to screen
(c) Several statements can be put on a line provided semicolons separate them.
In the above example, one can write the program as follows:
>>erasers=4; pads=6; discs=2;
>>items=erasers+pads+discs; cost=erasers*25+pads*52+discs*99
cost=
610
Instead of semicolons, one can use commas to separate statements. However, commas will not suppress writing to the screen
Predefined constants and functions
There are several predefined special constants and functions in Matlab
ans temporary variable containing the most recent answer.
eps specifies the accuracy of floating point precision
Inf infinity
pi the number π
i,j the imaginary unit [pic]
NaN undefined numerical value
Some Special Functions
Some of the commonly used functions are listed below. For additional list consult Help
max(x) largest component of array x
min(x) smallest component of array x
sin(x) trigonometric sine
cos(x) trigonometric cosine
sec(x) trigonometric secant
csc(x) trigonometric cosecant
tan(x) trigonometric tangent
cot(x) trigonometric cotangent
exp(x) Exponential
log(x) Natural logrithm
log10(x) log to the base 10
log2(x) log to the base 2
sqrt(x) square root
asin(x) inverse sine
acos(x) inverse cosine
atan(x) inverse tangent
asec(x) inverse secant
acsc(x) inverse cosecant
atan2(x) four quadrant inverse tangent
aength(x) computes the number of elements in array x
mean(x) computes the mean of x
std(x) computes the standard deviation of x
cosh(x) hyperbolic cosine =(exp(x)+exp(-x))/2
sinh(x) hyperbolic sine =(exp(x)+exp(-x))/2
tanh(x) hyperbolic tangent=sinh(x)/cosh(x)
coth(x) hyperbolic cotangent=cosh(x)/sinh(x)
sech(x) hyperbolic secant=1/cosh(x)
csch(x) hyperbolic cosecant=1/sinh(x)
acosh(x) inverse hyperbolic cosine
asinh(x) inverse hyperbolic sine
atanh(x) inverse hyperbolic tangent
acoth(x) inverse hyperbolic cotangent
acsch(x) inverse hyperbolic cosecant
asech(x) inverse hyperbolic secant
abs(x) absolute value of x
det(A) evaluates the determinant of matrix A
inv(A) evaluates the inverse of matrix A
cond(A) evaluates the condition number of matrix A
eig(A) evaluates the eigen-values of matrix A
Remarks
While programming in Matlab try not to use special constants as variable names
If you do not remember the name of a variable in a Matlab code, just type who. The variable in the above example are cost, items, discs, pads, and erasers.
Problems
1. Given x=5+4i and y=3-7i. Compute
U=x+y; v=x*y; w=x/y; p=xy^2; q=exp(y); r=(x)^.5
2.-(a ) The volume and surface area of a sphere are given by Vol=(4/3)πr 3 and S=4πr2 respectively, where r is the radius of the sphere. Use Matlab to determine the radius of a sphere with 30% more volume than that of radius 5 feet.
b) For the larger sphere does the surface area also increase by 30%?
( c ) Determine the radius of the sphere whose surface area is 30% larger than the surface area of a sphere of radius 5.
(d) Compare the results from (a) and (c).
M-files or Script files
Programming in Matlab can be carried out in two different ways
i) In the interactive mode where commands and statement etc are entered directly in the command window
ii) By running a Matlab program stored in script files. This type of file contains Matlab commands etc. and have an extension “.m”. So running it is equivalent to typing all the command one at a time in the command window. You can run the file by typing its name at the command window prompt.
iii) Use of “ …” at the end of a line will continue that statement to the next line. Good programming practice suggests that it is better break a large statement into several short statements.
How to write a script or M-file
In command window toolbar select New from File menu, then select M-file;
This opens up a new edit window—without >> prompt;
Type in the file or program—Can use Editor/Debugger to create or debug the file;
Then use Save from the File menu – Editor will automatically provide the “.m” extension and save it on the hard disc.
Example
% program example.m
%This program computes the cost of various items
erasers=4;pads=6;discs=2;
items=erasers+pads+discs; cost=erasers*25+pads*52+discs*pp;
average cost=cost/items
After this file is saved, it can be run any time in the command window by typing example after the prompt >>--Notice no “.m” extension is required while running the script file.
In-line Functions
Some times it is convenient to pass character string name of a function into a function (special function programmed by you) for evaluation.
There are several ways one can achieve this using eval, feval and inline.
Let us say you have created a script file called myfunc, then these functions will work as follows:
>>a=eval(‘myfunc(x)’);
or
>>a=feval(‘myfunc’,x);
In some cases the entire function is expressed as a character string in the program as:
Myfunc= “the math expression”,
In such situation feval does not work. However, one can use the other two ways of evaluation as:
>>a=eval(myfunc)
or
>>myinfun=inline(myfunc,’x’); % this converts myfunc to myinfun(x).
>>a=feval(myinfun,x)---now feval works
Examples---Note command window has >> prompt
(1)-------
Function y=myfunc(x)
% this is my function
y=x^3-2;
After saving this function file, in the command window
>>x=2;
>>a=feval(‘myfunc’,x)
a=
6
(2)
function f=myfunc(x,y)
% this is my function
f=10*(y-x)^2+(2-y)^2;
In command window
>>x=1; y=2;
>>a=feval(myfunc,x,y)
or
>>a=eval(myfunc(x,y)
a=
11
(3)---Note the single quote in defining myfunc below
>>myfunc=’10*(y-x)^2+(2-x)^2’;
>>x=1;y=2;
>>myinfun=inline(myfunc,’x’,’y’);
>>a=eval(myfunc)
or
>>a=feval(myinfun,x,y)
a=
11
(4)
function f=myfunc(x,y,t)
f1=10*(y-x)^2+(2-x)^2;
f2=5*x*t
f=[f1,f2];
Now feval etc will give two outputs
Remarks
When the function has to be computed many times in the execution of a program, feval is considered to be more efficient.
Problems
1. Write a script file to evaluate the following function:
Y=2+cos(πx) for –1 ≤ x ≤ 5;
Evaluate y for x=-.5, 3 and 4.5 and check your answer by hand.
Reading Input
Some times it is convenient to read in data rather than edit the code every time the data is changed. The following example shows this:
Example
% program example.m
%This program computes the cost of various items
erasers=4;pads=6;discs=input(‘enter number of discs’);
items=erasers+pads+discs; cost=erasers*25+pads*52+discs*pp;
average cost=cost/items
When this script is run in the command window, it will prompt you for the number of discs. Once the number is entered, the program will be executed and the result will be displayed.
Arrays
Matlab can handle the collection of numbers called arrays as if they were a single variable
>>x=[0,.1*pi,.2*pi,……,pi];
>>y=sin(x)
y=
Alternate Representation
>>x=(0:.1:1)*pi;
or
>>x=linspace(0,pi,10);
Array Orientation
>>c=[1;2;3;4;5]
c= 1
2
3
4
5
>> a=1:5
a=1,2,3,4,5
>>b=a’
b=1
2
3
4
5
>>c=b’
c=1,2,3,4,5
Remarks
Commas and spaces are used to separate elements in a row
Semicolons are used to separate rows
Array Operations
+ array addition
- array subtraction
+ scalar-array addition
- scalar-array subtraction
.* array multiplication
. / array right division
.\ array left division
. ^ array exponentiation
: represents entire row or column of an array
Example
>> a=[4,2]; b=[3,6]; c=2;
>>d=a+b
d=
[7,8]
>>d=a-c
d=
[1,-4]
>> d=a+c
d=
[6,4]
>>d=a-c
d=
[2,0]
>>d=a.*b
d=
[12,12]
>>a./b
d=
[4/3,2/6]
>>d=a.\b
d=
[4\3,2\6]
>>d=a.^b
d=
[4^3,2^6]
>>d=3.^a
d=
[3^4,3^2]
>>d=a.^3
d=
[4^3,2^3]
Matrix Representation
>>g=[1 2 3 4;5 6 7 8]
g=1 2 3 4
5 6 7 8
>>g-2
ans= each element will be subtracted by 2
>>a=[1,2,3;4,5,6;7,8,9]
>>b=[.1 0 .2;0 .3 1;.2 .4.6]
>>a+b=1.1 2.0 3.2
4.0 5.3 7.0
2. 8.4 9.6
>>a-b=0.9 2.0 2.8
4.0 4.7 5.0
6.8 7.6 8.4
Special Matrices
>>ones(3)
ans=1 1 1
1 1 1
1 1 1
>>zeros(2,5)
ans= 0 0 0 0 0
0 0 0 0 0
>>eye(3)
ans= 1 0 0
0 1 0
0 0 1
>>eye(2,4)
ans= 1 0 0 0
0 1 0 0
Problems
Let a=[7 14 –6;12 –5 9;-5 7 15];
b=[3 –2 1;6 8 –5;7 9 10];
1. Compute c=a+b; d=a+b+eye(3); f=a*b; g=a*one(3); h=one(3)*a;
p=a*eye(3); q=eye(3)*a;
Additional Vector and Matrix Computation
x = [1 2 3 ]
y = [5 10 15]
Addition and subtraction of vectors or matrices of the same dimensions are defined in the usual way
x + y = [1+5 2+10 3+15] = [7 12 18]
Component-by-component(scalar) product of vectors x and y is indicated as
x .* y = [(1)(5) (2)(10) (3)(15)] = [5 20 45]
Matrix transpose operation – denoted by a prime symbol, ‘
x ‘ = [ 1 y = [5 10 15]
2
3 ]
For this vectors x and y matrix multiplication is
x ’* y = [ (1)(5) (1)(10) (1)(15) [ 5 10 15
(2)(5) (2)(10) (2)(15) = 10 20 30
(3)(5) (3)(10) (3)(15) ] 15 30 15 ]
Polynomial Roots
In Matlab, one can define polynomials with an array whose elements are the polynomial coefficients.
Example
The polynomial x^3-7x^2+40x-34 will be represented by the array [1,-7,40,-34]. The polynomial roots can be obtained with a root finding function hard coded in Matlab.
>>a=[1,-7,40,-34];
>>roots(a)
ans=3.000+5.000i
3.000 -5.000i
1.000
Remarks
The number of roots is equal to the order of the polynomial
For polynomials with real coefficients, the complex roots always occur in conjugate pairs.
If we know the roots, the polynomial coefficients can be determined as:
>>x=[1,3+5i,3-5i];
>>poly(x)
ans=
1. -7 40 -34
If you wish to evaluate the value of a polynomial for certain value of x, the following command achieves this:
>> polyval(a,.8)
ans=
-5.9680
Polynomial addition
Let f=[5,-7,9,11];
g=[6,0,3];
g=[0,g];
f±g=[5±0,-7±6,9±0,11±3]; f+g →5x3-x2+9x+14
Product and Division of 2 Polynomials
Let f=[5,-7,9,11]; → 5x3-7x2+9x+11
g=[6,0,3]; →6x2+3
>>conv(f,g)= [30,-42,69,45,27,33]; →30x5-42x4+69x3+45x2+27x+33
>>[q,r]=deconv(num,den)=f/g, where
q=quotient=.8333, -1.1667 →.8333x-1.1667
r=remainder=0,-0,000,6.5,14.5→6.5x+14.5
Check: f=conv(q,g)+r
Remark
For addition and subtraction, the polynomials must be of the same order. For multiplication or division the order of polynomials can be different.
Example
The following equation appears in structural vibrations:
(α-f2)[(2α-f2)2-α2]+α2f2-2α3=0 ,
where α is the natural frequency k/(4π2m)
k=spring constant
m=mass
Clearly this equation can be treated in two different ways: (i) a cubic in f2, (ii) a 6th order equation. No matter how it is coded, the solution will be the same.
i) A cubic in f2=x→f= √x
p1=α-x
p2=2α-x
p3=α2x-2α3
→p1[p22-α2]+p3=0
Matlab code1
>>p1=[-1,α]; p2=[-1,2α]; p3=[α2,-2α3];
>>p4=conv(p2,p2)-[0,0,α2]; p5=conv(p1,p4)+[0,0,p3];
>> rt=roots(p5); f1=sqrt(rt); f2=-sqrt(rt);
ii) Matlab Code 2
p1=[-1,0,α]; p2=[-1,0,2α]; p3=[α2,0,-2α3];
>>p4=conv(p2,p2)-[0,0,0,0,α2]; p5=conv(p1,p4)+[0,0,0,0,p3];
>> rt=roots(p5)
Problems
1. Find the roots of the following polynomial
13x3+182x2-184x+2053=0,
use poly command to confirm your answer.
2. Find the roots of the polynomial
36x3+12x2-5x+10=0
use polyval command to confirm your answer.
3. Let the spring constant, k=4x106 Newtons/m and m=5000 kg
Write a Matlab code to find the roots of the 6th order equation given in the previous example.
Rational Operators
< less than
greater than
>= greater than equal to
= = equal to
~ = not equal to
Example
>>x=[6,3,8];
>>y=[12,1,9];
>>z= (x>z= (x>y)
z =
0 1 0
>>z=(x ~ = y)
z =
1 1 1
>>z =(x = = y)
z =
0 0 0
Other Relational Operators
>>z= x(x> x=[-2,0,4]
>>y=find(x); identifies the nonzero elements of array x
y=
1. 3;
The answer is that first and third elements of x are non zero
>> x=[6,3,9,11]; y=[14,2,9,13];
>>values=x(x>how_many=length(values)
how_many=
2
>>indices=find(x=0
y=sqrt(x);
end
(b)
if (x>0)&(y>=0)
z=sqrt(x)+sqrt(y);
end
(c) nested if statements
if(x>0)
y=x^1.5
if(y=0)
y=sqrt(x)
end
end
c) in example (b) elseif statement can be used more efficiently
if(x>=5)
y=log(x)
elseif x>=0
y=sqrt(x)
end
Remark
elseif statement does not require a separate end statement whereas else statement requires
Problems
1. Write a script file to evaluate the following function:
Y=ex+1 for x < -1;
Y=2+cos(πx) for –1 ≤ x ≤ 5;
Y=10(x-5) +1 for >5 .
Evaluate y for x=-5, 3 and 15 and check your answer by hand.
LOOPS
A loop is a structure for repeating a computation a number of times. Following three types of loops are usually used in Matlab.
i) Implied loops
Following statements contain implied loops
x=[0:.1:1];
y=sin(pi*x);
ii) for-loops
(a) for i=1:11
x = .1*(i-1);
y=sin(pi*x);
end
b) for i=1:1:11
x=.1*(I-1)
y=sin(pi*x)
end
In both (a) and (b) loop starts at i=1 and goes till 11 in steps of 1. The form (b) is a little more general. It can be used if the computations are say done at every three ‘i’ vales. Then the for statement will be:
For i=1:3:11
iii) while-loops
This type of looping is used when the loop terminates due to a specified condition. So we do not know a priori the number of passes required to satisfy the condition.
(a) x=2;
while x= 20
b) x=1
while x~=9
x=2x-1
end
the loop terminates when x~=9 is false for the first time
Remarks
The loop variable must have a value before while statement is executed.
The statements must change the loop variable somehow.
Problems
1. Use a while loop to determine how many terms in the series 2k , k=1,2,… are required for the sum to just exceed 1927.
Plot x-y plots
Ex.
x y
0 54.2
1 58.5
2 63.8
3 64.2
4 67.3
5 71.5
6 88.3
7 90.1
8 90.6
9 89.5
10 90.4
• >> plot(x,y)
title (‘Lab experiment #1’), xlabel (‘time,t’), ylabel (‘Temperature, degrees F’), grid
[pic]
c) Hold on command
x = 0: .1 : pi
y1=cos(pi*x) Remarks
Plot(x,y1), 2 plots on the same graph
y2=sin(pi*x);
hold on;
plot(x,y2)
[pic]
(b) Plotting
Graphs are generated by issuing the Matlab command
plot(x , y)
The following set of commands generates the graph below
x = 0 : 0.01 : 2 ; y = x^2 – 3
plot(x , y); hold on
xx = [0 2] ; yy = [0 0]
plot(xx , yy) ; grid on
hold off
[pic]
Output
• disp(variable)
Displays the value of variable without the variable name
Homework
A = 1 2 3 B = 1 0 2
4 5 6 2 1 0
7 8 7 0 3 1
i) Find A(3,3) and A(2,3)
ii) Find detA
iii) A + B
iv) B + A
v) A – B
vi) B – A
vii) A * B
viii) B * A
ix) A-1
x) A * A-1
xi) A-1 * A
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.