Вы находитесь на странице: 1из 57

Creating Arrays

What is an array
Referencing and changing single element in a
array
efe e i g a d ha gi g sli es of a a a
Built in function for handling arrays

Creating a Vector
Row_vector = [1 2 3 4 5]
Column_vector = [1;2;3;4;5]
Colon Operator
variable_name = m:q:n
Vector with constant spacing
variable_name = linspace(xi, xf, n)

Creating a Matrix
Variable_name = [1St row element; 2nd row
ele e t;..; last o ele e t]
Eg. A =[1 2 3;4 5 6;7 8 9]
B= [1:2:11;0:5:25;linspace(10,60,6);67 2 43 68 4 13]

Array Operations
clc; clear;
%Transpose of a matrix
A1=A
%array elements can be
accessed using subscripts
B=A(5)
C = A[1,2,4:6]

% access a block of
elements at one time
C=A(1:5)
D=A(6:end)

%reverse order
E=A(3:-1:1)

%to extract the elements


in any order
F=A([4 8 1 10])

%complex column vector


G=A2+A2*j
3/26/2016

Lecture Notes for MATLAB for Engineers

A(:,j)
Colon
Operator : A(i,:)
A(:,:)

Enter a
A(j:k)
5x5
matrix and A(:, j:k)
use colon A(:)
operator

jth

column of A
ith row of A
same as A
A(j), A(j+1),...,A(k)

A(:,j), A(:,j+1),...,A(:,k).
all the elements of A, regarded as a
single column

A(m:n, p:q)

Refer to the element in rows m through


n and columns p through q of matrix A

A(:,2)=[]
A (1,:)=[]

Deletion of rows and columns

B = A(:, 1:5);

Read columns 1-5 of all rows

B=A([1,3],[1,3,4,5])

3/26/2016

Lecture Notes for MATLAB for Engineers

Problems
1.
2.
3.
4.

Create a row vector in which first element is 1 and last element is 33 an


increment of 2 between the element.
Create a column vector in which first element is 15 and last element is -25
an increment of -5 between the element.
Create a row vector with 15 equally spaced element in which first element is
7 and the last element is 40.
6
43 2
11 87
Create the following matrix A
12

35

34

18

a) Create a five element row vector named va that contains the element of
second row A.
b) Create a three element row vector named vb that contains the element of
fourth column A.
c) Create a ten element row vector named vc that contains the element of first
and second row of A.
d) Create a ten element column vector named ud that contains the element of
second and third row of A.

Problems Cont.

5. Create a following matrix C

10

12

14

21

18

15

12

10

15

20

25

30

35

Create a 3 * 4 matrix B from 1st , 3rd and 4th rows, and 1st ,3rd , 5th and 7th
columns of matrix A
b) Create a 15 element long row vector u from the elements of the 3rd row,
3rd , 5th and 7th columns of matrix A
c) Create a 3 * 5 matrix C from 2st , 3rd and 4th rows, and 2st through 6th
columns of matrix A
6. Using the zeros and ones command create a 3 * 5 matrix in which 1st , 2nd
and 5th columns are zeros and 3rd and 4th columns are ones.
a)

Problems Cont.
7.Create a 6 * 6 matrix in which the middle two rows, and the middle two columns
a e s a d est a e s.
Given are a 5 *6 matrix A, a 3 * 6 matrix B, and a 9 element long vector v.

A=

11 14 17

12 15 18

10 13 16 19

11 14 17 20

12 15 18 21

V=

99

98

97

10 15 20 25 30

B = 30 35 40 45 50 55
55 60 65 70 75 80

96

95

94

93

92

91

Create the three arrays in the Command Window, and then , by writing one
command ,replace the last four columns of the 1st and 3rd rows of A with the first
four columns of the first two rows of B, the last four columns of the 4th row of A
with the elements 5 through 8 of v, and the last four columns of the 5th row of A
with columns 3 through 5 of the third row of B.

8.Using the eye command create the array A shown on the left below using the colon
to address the elements in the array, change the array to be like the one shown on the
right.

A=

Built- In Function for handling Arrays


Length(A)
Size(A)
reshape(A, m, n)
diag(A)
ones(m,n)
zeros(m,n)
Eye(m,n)

A=

Mean(A) A is a vector

Sum(A)

Sort(A) arrange the vector in ascending


order

std(A) standard deviation of the vector

Det(A)

Inv(A)

Mathematical operation with array


1.

Solve three linear equations.


4x 2y + 6z = 8
2x + 8y + 2z = 4
6x + 10y + 3z = 0
2. Define x and y as the vectors x = 2, 4, 6, 8, 10 and y = 3, 6, 9, 12, 15. Then use
them in the following expression to calculate z.
=

3. The coefficient of friction can be determined in an experiment by measuring


the force F required to move a mass m. When F is measured and m is known the co
efficent of friction can be calculated by =
= . /

Result for measuring F in six tests are given in table below. Determine the coefficient of friction in each test and the average from all tests.
Test

Mass m (kg)

10

20

50

Force F (N)

12.5

23.5

30

61

117

294

4. Use MATLAB to show that the sum of infinite series

Converges to ln2. do this by computing the sum for:


a) N = 50
b) N = 500
c) N = 5000
5 A projectile is fired with a muzzle speed of 500 m/s. Calculate the distance
d that projectile will hit the ground if the firing angle is changed from 5o to
85o in 5o increments. To show the results create a 17 * 2 matrix in which the
elements in the first column are the firing angles and the elements in the
second column are the corresponding distances rounded to the nearest
integers. Also find the maximum distance covered.

Two-Dimensional Plots
The plot command is use to create two-dimensional plot.
Plot , , line specifiers , Property name , Property value
Line Specifiers
Line
Style

Solid
(default)
Dashed
Dotted

Specifier

-:

Dash-dot -.

Line
color

Specifier

red

Green

blue

cyan

magenta m
yellow

black

white

Marker Type

Specifier

Plus sign

Circle

Asterisk

Point

Square

Diamond

Five-pointed
star

Six-pointed
star

Property name and property value


Property Name

Description

Possible property value

Linewidth

Specifies the width of


the line

A number in units of
points (default 0.5)

Marker size

Specifies the size of the


marker

A number in units of
points

Markeredgecolor

Specifies the color of the Color specifiers from the


marker or the color of
table above, typed as a
string
the edge line for filled
markers

Markerfacecolor

Specifies the color of the Color specifiers from the


filling for filled markers
table above, typed as a
string

Eg. Plot , , --d , linewidth , , markersize , , markeredgecolor , ,


markerfacecolor , g
Plotti g ultiple g aph i sa e plot usi g hold o a d hold off

Formatting a plot using Commands


Xlabel

Xlabel te t as stri g

ylabel

Ylabel te t as st i g

title

title te t as st i g

gtext

gtext te t as st i g

legend

lege d te t , te t , te t

axis

Axis( [ xmin, xmax, ymin, ymax ] )

Grid on ,
Grid off

Add or remove grids lines

Formatting the text in the Xlabel, Ylabel, Text and Legend command
Modifier

Effect

\bf

Bold font

\it

Italic font

\rm

Normal font

\fontname{fontname}

Specified font is used

\fontsize{fontsize}

Specified font size is used

Greek characters
Characters in the string

Greek Letter

Characters in the string

Greek Letter

\alpha

\Phi

\beta

\Delta

\gamma

\Gamma

\theta

\Omega

\pi

\Sigma

1.

2.

3.

A circuit with seven resistor of 2, 4, 6, 8, 10, 12 and 14 ohms are


connected in series. Write a program in a script file that calculate the
voltage across each resistor and the power dissipated in each resistor.
When the script file is executed it request the user to first enter the
source voltage and then then to enter the resistance of the resistor in
vector. The program display a table with resistance listed in first column,
the voltage across the resistor in second column and the power
dissipated in the resistor in the third column. Following the table the
program displays the current in the circuit and the total power.
The velocity v and distance d as a function of time of a car accelerates
from rest at constant acceleration of 2 m/s2. Determine v and d as every
second for the first 10 seconds. Display the results in three- column table
in which the first column is time, the second distance and the third is
velocity.
a. Make two separate plot of the function f(x) = 0.6x5 5x3 +9x +2; one
plot for - , a d o e fo - . . . La el the a is a d gi e a title
b. Plot on the same graph
c. Plot using subplot

4. The position x as a function of time of a particle that moves along a curve


given by x(t) = 0.4t3 2t2 -5t + 13 m. Derive the expression for velocity and
acceleration of the particle and make plots of position, velocity and
a ele atio as a fu tio of ti e f o
t s. Use the su plot o
a d
to make three plots on the same page with the plot of position on the top ,
the velocity at the middle and the acceleration at the bottom. Label the axe
appropriately with the correct units.
5. An electrical circuit that includes a voltage source Vs with internal
resistance rs , and a load resistance Rl is shown in the figure. The power P
dissipated in the load is given by
=

Plot power P as a function of Rl fo


= 2.5 ohms

Rl

oh s, gi e that Vs =

V a d rs

Function and Function File


The form of Function definition line is

function [ output argument] = Function_name (input argument)


The word function must be the first word and must be typed in
lower case letters
Output argument is the list of output variable typed inside brackets
Function_name is the name of the function
Input argument is the list of input variable typed in the parenthesis
Eg.
function[mpay, tpay] = loan(amount, rate, years)
function[A] = rectarea(a, b)
function[v, s] = spherevolarea(r)
function trajectory(v, h, g)
When a function file is saved , the name of the file should be the
same as the name of the function.

1.Write a function file ( chp6one) for

+
+

.The input to the function x

and the output is f(x). Write the function such that x can be vector. Use the
function to calculate:
a) For x = 6
b) For x = 1, 3, 5,9,11
2. Write a user-defined function (FtoC) that converts the temperature in degree F
to temperature in degree C. Use the function to solve the following problem. The
ha ge i the le gth of a o je t L, due to a ha ge i the te pe atu e T is
given by L = L T, where is the coefficient of thermal expansion. Determine the
change in the area of a rectangle ( 4.5 m by 2.25 m) aluminum ( = 23 * 10-6 ) plate
If the temperature changes from 40o F to 92o F.
3. Create a function file that calculates the trajectory of a projectile. The inputs to
the function are initial velocity and the angle at which the projectile is fired. The
outputs from the function are the maximum height and the distance. In addition
the function generates a plot of the trajectory. Use the function to calculate the
trajectory of a projectile that is fired at a velocity of 230 m/s at an angle of 39o.

4. In a low pass RC filter (a filter that passes signal of low frequency), the ratio of
the magnitude of voltages is given by

Where w is the frequency of the input signal.


Write a user-defined MATLAB function that calculate the magnitude ratio. For the
function name and argument us RV = lowpass(R,C,w). The input argument are R in
ohms, Capacitance C in Farad and w the input frequency in rad/s. Write a program
in script file that uses the lowpass function to generate a plot of RV as a function of
w for 10-2 6 rad/s. The plot has a long arithmetic scale on the horizontal
axis. When the script file is executed it ask the user to enter the value of R and C.
Label the axis and also give it a title. Run the script file with R= 1200 ohms and
C=8 F.
5. Write a user defined function that determine the angles of a triangle when the
lengths of sides are given. For the function name and argument use [
]=triangle(a, b, c) .Use the function to determine the angles in triangles in degree
with following sides.
a) a=10, b=15, c=12
b) A=6, b=8, c=10
c) A=200, b=75, c=25

Relational Operators
The relational operators are <, >, <=, >=, ==, and
~=
Relational operators perform element-by-element
comparisons between two arrays.
They return a logical array of the same size, with
elements set to logical 1 (true) where the relation
is true, and elements set to logical 0 (false)
where it is not.
If one of the operands is a scalar and the other a
matrix, the scalar expands to the size of the
matrix.
The logical operator (and) &, (or) |, (not) ~

Precedence

Operation

Parenthesis

Exponentiation

Logical Not

any(A>=X)
find(A)%non-zero elements
find(A>X)

Multiplication and
Division

Addition and
Subtraction

find(0 < A & A < 0.1*pi)

Retational
operators

Logical operator

EXAMPLE
A = [0.53 0.67 0.01 0.38 0.07 0.42
0.69];
X=0.02;
xor(X,A)

all(A>=X)

The following were the daily temperature in Mangalore during the month of April.
58, 73, 73, 53, 50, 76, 50, 50, 73, 66, 69, 74, 82, 84, 91, 93, 91, 89, 64, 56, 78, 89,
67, 45, 67, 89, 34, 69, 69, 68.
Use relational and logical operator to determine
a) The number of days temperature was above 75
b) The number of days temperature was between 65 and 80
c) The days of the month that the temperature was between 50 and 60
X = 2 ; y = 5;
FIND -5< x< -1;

-5< x & x <-1

~(y<7)
~((y>=8)|(x<-1))
~(y>=8)|(x<-1)

r= [8 12 9 4 23 19 10]; w=r(r<=10)

The maximum daily temperature ( in oF ) for New York City and Alaska during the
month of January, 2001 are given in vector below.

N 3 2 3 3 3 3 4 4 4 4 3 3 5 4 4 4 4 4 3 3 3 4 4 5 5 5 5 5 4 3
Y 1 6 0 3 3 9 0 2 4 5 8 6 0 9 6 4 3 2 7 8 9 0 2 4 5 6 7 8 2 7
A 3 2 2 2 2 3 3 3 3 4 4 3 2 3 4 2 4 3 3 3 4 2 2 3 3 3 4 4 2 2
L 7 4 5 8 6 7 6 2 4 1 2 5 8 9 0 4 0 4 2 6 0 8 9 1 4 6 2 1 2 5

Write a program in script file to answer the following


a) Calculate the average temperature for the month in each city.
b) How many days was the temperature below the average temperature in each
city.
c) How many days and, and which dates in the month, was the temperature in
Alaska higher then the temperature in New York.
d) How many days, and which date in the month, was the temperature same in
both city.
e) How many days, and which dates in the months temperature in both cities
above freezing (above 33 oF).

Condition Statement
A condition statement is a command that allows the MATLAB to make a decision
of whether to execute a group of command that follow the conditional statement
or to skip these commands.
In a conditional statement a condition expression is stated
If the expression is true, a group of commands that follow the statement is
executed.
If the expression is false the computer skip the group.
if (condition expression consisting of retational and/or logical operator)
Examples
If a<b
If c>=5
All the variable must have assigned values
If a = b
If (d<h) && (x>7)
Condition statements can be part of a program written in script file or a function
file
For every IF statement there is an end statement

The if end structure


Matlab program
If condition expression

. A g oup of Matlab command


.
end
..
Matlab program
.
Eg.
A worker is paid according to his hourly wage up to 40 hours, and 50% more for
overtime. Write a program in script file that calculates the pay to a worker. The ask
the user to enter the number of hours and the hourly wages. The programmer than
display the pay.

The if else end Structure


MATLAB program
If (condition expression)

G oup of MATLAB command


else

. Group2 of MATLAB command


end
MATLAB p og a

Write a user-defined function file that calculates the value of z. The input to the
function are x and y . Write the function such that x and y can be vector. If any
element of x is greater than y then z = x2/y otherwise z=(x-y)2/(y2+1). The input to
the function is x , y vector and output is z vector.

The if elseif else-end Structure


MATLAB program
If (condition expression)

G oup of MATLAB o
a d
elseif (condition expression)

. G oup of MATLAB command


else

. G oup of MATLAB o
a d
end
MATLAB p og a
The else statement is optional
Several elseif statement and associated group of command can be added

Write a program in a script file that determine the real roots of a quadratic
equation ax2 + bx +c =0. Name the file quadroots. When the file runs it ask
the user to enter the values of the constant a, b and c.
If D > the p og a displa a essage: the e uatio has t o oots a d the
roots are displayed in the next line.
If D = the p og a displa a essage: the e uatio has equal oots a d the
roots are displayed in the next line.
If D < the p og a displa a essage: the e uatio no real oots a d the
roots are displayed in the next line.
2x2 + 8x -3 = 0
15x2 + 10x +5 =0
18x2 +12x + 2 = 0

For Loop: Execute statements for specified number of times /


repeat an operation for a known number of iterations

for k= f :s : t
run loop
end

k - Loop index variable


f - The value of k in the first
pass
s - The increment in k after
each pass
t - the value of k in the last
pass

Eg.
for counter = 1:n
run loop
end

clear; clc;
%program to find sum of the
first n numbers of the series
n=20;
s=0;%setting the sum to zero
for k=1:n
s=s+(-1)^k*k/(2^k);
end
s
Ans: -0.2222

1.

2.

3.

4.

Use a for end loop in a script file to calculate the sum of the first n terms of

the series sin =

Use loop to create a 4 * 7 matrix in which the value of each element is the sum
of its indices ( the row number and column number of the element). For
example, the value of element A(2, 5) is 7.
Use loops and condition statement to create a 5 * 8 matrix in which the value
of each element is equal to the square root of the sum of element of indices
unless the element is a even-numbered column or row. The value of the
element in a even numbered column or row is equal to the sum of the
elements indices squared. The indices of an element in a matrix are the row
number and column number of the elements.
A vector is given by x = [15 -6 0 8 -2 5 4 -10 0.5 3]. Using condition statements
and loops write a program that determines the sum of the positives elements
in the vector.

SYNTAX

LOG(N) >10 WHERE N STARTS


WITH 1

while condition 1==true


run loop
end

Fixed number or iteration-FOR


loop
Iterate until condition is reached WHILE loop

Start with n=1


Until log(n) >10
Replace n with n+1
Display n

clc;clear;
n = 1;
while log(n) < 10
n = n + 1;
End
Disp(n)

3/26/2016

Lecture Notes for MATLAB for Engineers

33

1.Write a program in script file that determines ex by using the Taylor series
representation. The program calculates ex by adding terms of the series and
stopping when the absolute value of the term that was added last is smaller than
0.0001. Limit the number of passes to 30. If in the 30th pass the value of the term
that is added is not smaller than 0.0001 the program stops and displays a message
that more than thirty terms are needed.
Use the program to calculate e2, e-4 and e21
ex = 1 + x + x2/ +..
2. Write a program (using a loop) that determines the sum of first m terms of the
series. =
+

Run the program with m=10 and m = 500. Compare the result with /4.
3. Write a program in a script file that find the smallest odd integer that is divisible
by 3 and whose cube is greater than 4000. The loop should start with 1 and stop
he the u e is fou d. The p og a p i t the essage: the e ui ed u e
is a d the p i ts the u e .

4.Write down a user defined function that sorts the elements of a vector (of any
length) from the largest to smallest. For the function name and argument use Y =
downsort(X). The input to the function is a vector X of any length and the output Y
is a vector in which the elements x are arranged in descending order. Do not ue
Matlab sort function. Test your function on a 14 element(integers) randomly
distributed between -30 and 30. Use the rand command to generate the matrix.
5.Write a user-defined function that determines the polar coordinates of a point
from the Cartesian coordinate in a two=dimensional plane. For the function name
and argument use [theta radius]=cartesiantopolar(x,y). The input argument are the
x and y coordinates of the point and the output argument are the angle and the
radial distance to the point. Use the function to determine the polar coordinates of
points (15,3), (-7,12), (-17,-19) , (10,-6.5), (0,-3)
6. Write down a user defined function that sorts the elements of a matrix. For the
function name and argument use B = matrixsort1(A), where A is any size matrix and
B is a matrix of the same size with the elements of a rearranged in an ascending
order row after row where the (1,1) element is the smallest and the (m,n) element
is the largest.
Test your function on a 4*7 matrix element(integers) randomly distributed between
-30 and 30. Use the rand command to generate the matrix.

A cylindrical vertical fuel tank has hemispheric end caps as shown. The radius of
the cylinder and the caps is r = 40cm, and the length of the cylindrical part is 1.2 m.
Write a user-defined function (for the function name and arguments use V
=Vfuel(h) ) that gives the volume of the fuel in the tank as a function of height h.
Use the function to make a plot of of the olu e as a fu tio fo h
.

Switch Case
SYNTAX
switch (switch_expression )
case (case_expression
statements )
case (case_expression
statements )
:
otherwise
statements
end

A switch block
conditionally executes one
set of statements from
several choices. Each choice
is a case. When a case is
true, MATLAB executes the
corresponding statements,
and then exits the switch
block. Otherwise is
optional, and executes only
when no case is true.

Write a program in script file that converts a quantity of energy (work) given in
units of either joules, ft-lb, cal, or eV to equivalent quantity in different unit
specified by the user. The program ask the user to enter the quantity of energy,
its current units, and the new desired unit. The output is the quantity of energy
in the new units.
J= ft-lb/0.738
J= cal/0.239
J=eV/(6.24 *1018)
convert 150J to ft-lb
2800 cal to Joules
2.7 eV to cal

Write a program in a script file that calculates the cost of mailing a package
according to the following prices schedule using Switch Case statement.
Type of service

Weight
(0-2 Kg)

Weight
(2-10 Kg)

Weight
(10-50 Kg)

Ground

200

200+ 25 for each additional 1 Kg


above 2 Kg

400+ 20 for each additional 1Kg


above 10 Kg

Air

300

300+ 50 for each additional 1 Kg


above 2 Kg

700+ 40 for each additional 1Kg


above 10 Kg

Over-night

500

500+ 100 for each additional 1


Kg
above 2 Kg

No over-night service

The programmer ask the user to enter the weight and type of service. If a weight
la ge tha
Kg is e te ed fo g ou d o ai se i e a essage G ou d o Ai
se i es is ot a aila le is displa ed. If a eight la ge tha
Kg is e te ed fo
overnight service a message O e ight services is not a aila le

Polynomials
Polynomials are function that have the form

F(x)=an xn + an-1xn-1 + .. +a1x +ao


Polynomial
F(x) = 5x5 +6x2 + 7x +3
F(x) = 2x2 -4x +3

Matlab representation
p=[5 0 0 6 7 3]
q=[2 -4 3]

Value of a Polynomial
The value of a polynomial can be calculated with the function poly-val
Polyval (P, x)
P is a vector with the coefficient of the polynomial
X is a n number or a variable that has an assigned value or a computable expression
X can be vector or a matrix
F(x) = x5 -12.1x4 + 40.59x3 - 17.015x2 71.95x +35.88
Calculate f(9)
Plot the polynomial for - . .

Roots of polynomial
Roots of a polynomial are the value of the argument for which the value of the
polynomial is equal to zero.
r = roots (p)
r is a column vector with the roots of the polynomial
p is a row vector with the coefficient of the polynomial
F(x) = x5 -12x4 + 37x3 - 43x2 x +2
Addition, Multiplication of polynomial
Addition
Two polynomial are added by adding the vector of the coefficient.
If the polynomial are not of the same order, the shorter vector has to be
modified to be of the same length as the longer vector by padding with zeros.
F(x) = x5 -12x4 + 37x3 - 43x2 x +2
F(x) = 2x2 -4x +3
Multiplication
Two polynomial can be multiplied with the Matlab built in function conv
c = conv ( a, b )
c is a vector of coefficient of the polynomial that is the product of multiplication
a and b are a vector of coefficient of the polynomial that are being multiplied

Division

A polynomial can be divided by another polynomial with the Matlab


built- in function deconv
[q , r] = deconv (u , v)
q is a vector with the coefficient of the quotient polynomial
r is a vector with the coefficient of the remainder polynomial
u is a vector with the coefficient of the numerator polynomial
v is a vector with the coefficient of the denominator polynomial
Derivative of a polynomial
The built in function polyder can be used to calculate the derivative of
a single polynomial, a product .of polynomials and a quotient of two
polynomial
K = polyder ( p )
K = polyder (a , b)
[n , d] = polyder( a , b)

1. Write a user-defined function that adds or subtracts two polynomials of any


order. Name the function p= polyadd p ,p , ope atio . The fi st t o i put
arguments p1 and p2 are the vectors of the coefficients of the two polynomials. ( If
the two polynomials are not of the same order the function adds necessary zero
elements to the shorter vector. The third input argument is a string that can be
eithe add o su fo addi g o su t a ti g the pol o ials, espe ti el a d the
output argument is the respective polynomials.
f1(x) = x5 7x4 + 11x3 -4x2 -5x -2
f2(x) = 9x2 -10x +6
2. Write a user define function that calculate the maximum (or minimum) of a
quadratic equation of the form f(x) = ax2 + bx + c.
Name the function [x, y, w]= maxormin (a, b, c). The input argument are the
coefficients a, b and c. The output argument are x the coordinates of the maximum
(or minimum). Y is the maximum (or minimum) value, and w which is equal to 1 if y
is a maximum, and equal to 2 if y is a minimum.
Use the function to determine the maximum or minimum of the following
function.
a) f(x) = 6x2 -18x + 6
b) f(x) = -4x2 -20x + 5

Curve Fitting
Curve fitting, are called regression analysis, is a process of fitting a
function to a set of data points.
Curve fitting with polynomials is done in Matlab with the polyfit
function, which uses the least square method.
P = polyfit( x, y, n)
P is the vector of the coefficient of the polynomial that fits the data
x is a vector with horizontal coordinate of the data points
(independent variable).
y is a vector with vertical coordinate of the data points (dependent
variable).
n is the degree of the polynomial.
For the same set of m points, the polyfit function can be used to fit
polynomials of any order up to m-1.

Function
Power
(x, y logarithmic)

y = bxm

POLYFIT
FUNCTION FORM
P = polyfit( log(x) , log(y), 1)

Exponential
y = bemx
(x linear & y logarithmic) y = b10mx

P = polyfit( x , log(y), 1)
P = polyfit( x, log10(y), 1)

Logarithmic
y = m ln(x) +b
(x logarithmic & y linear) y = m log(x)+b

P = polyfit( log(x) , y , 1)
P = polyfit( log10(x) , y, 1)

Reciprocal
y = 1/ (mx +b)
(x linear & 1/y linear)

P = polyfit( x , 1./y, 1)

Other considerations when choosing a function are


Exponential function cannot pass through origin
Exponential function can only fit data with all positive
s o all egati e s
Logarithmic function cannot model x = 0 or negative
values of x
For power function y = 0 when x = 0
The reciprocal function cannot model y = 0

The following points are given


x

-5

-4

-2.2

-1

2.2

0.1

0.2

0.8

2.6

3.9

5.4

3.6

2.2

3.3

6.7

8.9

a)

Fit the data with a first order polynomial. Make a plot of the points and the
polynomial.
b) Fit the data with a third order polynomial. Make a plot of the points and the
polynomial
c) Fit the data with a fourth order polynomial. Make a plot of the points and the
polynomial
d) Fit the data with a tenth order polynomial. Make a plot of the points and the
polynomial

1.The population of China from the year 1940 to the year 2000 is given in the
following table:
Year

1940

Population
537
(millions)

1950

1960

1970

1980

1990

2000

557

682

826

981

1135

1262

a)

Determine the exponential function that best fits the data. Use the function to
estimate the population in 1955.
b) Curve fit the data with a quadratic equation and estimate the population in
1955.
2. An electrical capacitor has an unknown capacitance. In order to determine the
capacitance the switch is closed and the capacitor discharge through the resistor
(200 ohms). As the capacitor is discharging, the voltage across the capacitor is
measured for 10 s in intervals of 1s. The recorded measurement are given in the
table below. Plot the voltage as a function of time and determine the capacitance of
the capacitor by fitting an exponential curve to the data points.
t(s)

10

v(V)

9.4

7.31

5.15

3.55

2.81

2.04

1.26

0.97

0.74

0.58

Viscosity, is a property of gases and fluids that characterize their resistance to flow.
For most material viscosity is highly sensitive to temperature. Below is a table that
gives the viscosity of SAE 10W oil at different temperatures. Determine an equation
that can be fitted to the data. This function can be fitted to the data by using Matlab
polyfit (x, y, 2) function (second degree polynomial) where independent variable is T
and the dependent variable is ln().
T (o C )
Ns/
(10-5)

2)

-20

20

40

60

80

100

120

0.38

0.095

0.032

0.015

0.0078

0.0045

0.0032

Interpolation
Interpolation is estimation of values between data points.
One- dimension interpolation in Matlab is done with the interp1 function which has
the form:

yi = i terp1 , , i,

ethod

yi is the interpolated value


x is a vector with the horizontal coordinate of the input data points (independent
variable)
y is a vector with the vertical coordinate of the input data points
xi is the horizontal coordinate of the interpolation point (independent variable)

The vector x must be monotonic.


xi can be a scalar or a vector. Respectively, yi is a scalor or a vector
with the corresponding interpolated values.

The Matlab can do the interpolation using one of several methods. These method
include
nearest

Return the value of the data point that is nearest to the interpolated
point

linear

Uses linear spline interpolation

spline

Uses cubic spline interpolation

pchip
cubic

Uses piecewise cubic Hermite interpolation

Whe the earest a d the li ear ethods are used the alue of i ust e
ithi the do ai of . If the spiline or the pchip ethods are used, i a
have value outside the domain of x and the function interp1 perform
extrapolation
The spiline ethod a gi e large errors if the i put data poi ts are o uniform such that some points are much closer than others.
Specification of the method is optional. If no method is specified the default is
li ear,.

1. The following data points which are the points of the function f(x) = 1.5xcos(2x)
are given. Use linear, spline, and pchip interpolation methods to calculate the value
of y between the points. Make a figure for each of the interpolation methods. In
the figure show the points, a plot of the function, and a curve that corresponds to
the interpolation method.
x

-0.6242

-1.4707

3.2406

-0.7366

-6.3717

2. The yield strength y of many metal depends on the size of the grains. For these
metals the relationship between the yield stress and the average grain diameter d
can be modeled by the Hall-Petch equation.
y = o +k d-1/2
The following are results from measurements of average grain diameter and yield
stress.
d (mm)

0.005

0.009

0.016

0.025

0.04

0.062

0.085

0.11

205

150

135

97

89

80

70

67

a. Use linear interpolation to determine the yield stress of material with grain size
of 0.005 mm. Make a plot that shows the data points with circle markers and
linear interpolation with a solid line.
b. Use cubic interpolation to determine the yield stress of material with grain size
of 0.005 mm. Make a plot that shows the data points with circle markers and
linear interpolation with a solid line.

Three-Dimensional plot
Three-dimensional (3-D) plots can be used to represent data that consists of more
that two variable.
A basic 3-D plot is created with the plot3 command
Plot3( x, y, z line specifiers , Property name , Property value
x, y, z are vectors of the coordinates of the points
The line specifiers, properties and property value are same as in 2-D plots.
Eg.
x=

sin(2t)

y= cos(2t)
Z=0.5t
Mesh and Surface plot
Mesh and surface plots are three-dimensional plots that are used for plotting
functions of the form z = f(x , y) where x and y are independent variable and z is the
dependent variable.

Creating a grid in x-y plane


The grid is a set of points in the x-y plane in the domain of the function.
For example - a d y 4
The grid of the points can be defined by two matrix X and Y.

X=

-1

-1

-1

-1

Y=

The X matrix is made from identical row since each row the points have the
same x coordinates. In the same way the Y matrix is made from identical
columns since each column the y coordinates of the points is the same.
Matlab has a built in function called MESHGRID that can be used for creating
the X and Y matrices.
[X, Y] = meshgrid(x , y)
Once the grid matrix exist they can be used for calculating the value of Z at
each grid points.

Once the three matrix exist they can be used to plot mesh and surface plots.
A mesh or a surface plot is created with the mesh or surf command
Mesh(X , Y , Z) and surf(X , Y , Z)
Example
=

over the domain - a d .

x=-1:0.1:3;
y=1:0.1:4;
[X,Y]=meshgrid(x,y);
Z=(X.*Y.^2)./(X.^2+Y.^2);
Figure(1)
Mesh(X,Y,Z)
Figure(2)
Surf(X,Y,Z)

Meshz, Meshc, Surfc, Surfl, waterfall, contour3(X,Y,Z,n), contour(X,Y,Z,n)

1.The position of a moving particle as a function of time is given by


x=(2+4cos(t))cos(t)
y=(2+4cos(t))sin(t)
z=t2
Plot the position of the particle for 0 t 20
2. Make a 3-D surface plot and a 3-D contour plot of a function
=

in domain - a d

Оценить