ASCII CodesEach character in a string is one element in an array that requires two bytes per character forstorage, using the ASCII code.. >> text = ’This is a character string’ This is a
Trang 1then g(x)is the derivative of f (x)with respect to x This relationship is written as
Figure 11.6: Derivative of f (x)at x = a.
Formally, the derivative of f at x is
f (x)= lim
∆x→0
f (x + ∆x) − f(x) (x + ∆x) − x = lim∆x→0
approx-approximation of the slope of the tangent line can be done in several ways, as shown in Figure 11.7
The backward difference approximation of the derivative at x k is the slope of the line between
f (x k−1 )and f (x k), as shown in Figure 11.7a
The forward difference approximation of the derivative at x k is the slope of the line between
f (x k )and f (x k+1), as shown in Figure 11.7b
f (x
k) = f (x k+1)− f(x k)
x k+1 − x k
Trang 2For uniform spacing ∆x
f (x
k) = f (x k+1)− f(x k)
∆x Note that the forward difference at x k is the same as the backward difference at x k+1.
Figure 11.7: Techniques for approximating f (x k).
The quality of both of these derivative approximations depends heavily on two factors: the spacing
of the samples and the scatter in the data due to measurement error The greater the spacing, themore difficult it is to estimate the derivative The approximation improves as the spacing betweenthe two points decreases
The central difference is the average of the forward and backward differences For uniform
This average tends to cancel out the effects of measurement error
The second derivative of a function f (x)is the derivative of the first derivative of the function
f (x
k) = df
(x) dx
This function can be approximated using slopes of the first derivative Using backward differences
and assuming uniform spacing ∆x
Trang 3Obviously, in this example, since samples of x are spaced by 1, dy and df are the same.
Note that the values of df are correct for both the forward-difference and the backward-differenceapproximation to the derivative, as explained above The distinction between the two methods ofapproximating the derivative is determined by the values of x that correspond to the derivative
dy Since dy has length one less than that of x, it must be related to a vector xd that is thevector x truncated by one sample at either the beginning or the end The backward-differenceapproximation of the derivative is related to x truncated at the beginning:
Trang 4The backward difference and central difference methods can be compared by considering a sinusoidalsignal that is measured 51 times during one half-period The measurements are in error by aGaussian distributed error with standard deviation of 0.025 Figure 11.2 shows the measured dataand the underlying sine curve The following script implements the two methods The results areshown in Figure 11.2 Clearly the central difference method provides better results in this example.
% Comparison of numerical derivative algorithms
0.2 0.4 0.6 0.8 1
x
Figure 11.8: Measurements of a sine signal containing Gaussian distributed random errors
Example 11.2 Numerical differentiation of a polynomial function
Trang 50 0.5 1 1.5 2 2.5 3
−2
−1 0 1
x
True derivative Backward difference
0 0.5 1 1.5 2 2.5 3
−2
−1 0 1 2
x
True derivative Central difference
Figure 11.9: Comparison of backward difference and central difference methods
Determine the linear acceleration of an object whose speed is defined by s(t) = t3− 2t2+ 2 m/s,
where t is in seconds, over the interval 0 to 5 Determine the specific acceleration at t = 2.5s.
Consider computing the derivative function at three different resolutions to determine the effect of
increasing the resolution Begin with a time resolution of ∆t = 0.1 second, compute the speed at
each of the time values and compute the acceleration by approximating the derivative of the speedwith respect to time:
>> t = 0:0.1:5;
>> s = t.^3 - 2*t.^2 + 2;
>> ds = diff(s)./diff(t);
To determine the acceleration at t = 2.5s, it is first necessary to find the time index corresponding
to this time Relating t to find the index k and the time interval ∆t:
Trang 6>> ds(26)
ans =
9.3100
Thus, the acceleration is 9.31 meters/second2.
Repeating the computations for ∆t = 0.01 second:
Note that the result decreases with each decrease in the time interval To check the answer,
analytically differentiate s(t)to obtain:
s (t) = 3t2− 4t
At t = 2.5s:
s (2.5)= 3(2.5)2− 4 · 2.4 = 8.75m/s2
Trang 7Thus, we observe that the approximation is converging to the correct result.
Since theMatlab diff function returns only an approximate derivative, it is necessary to use theresolution required to achieve the accuracy desired
Differentiation Error Sensitivity
Differentiation is sensitive to minor changes in the shape of a function, as any small change in thefunction can easily create large changes in its slope in the neighborhood of the change
Because of this inherent sensitivity in differentiation, numerical differentiation is avoided wheneverpossible, especially if the data to be differentiated are obtained experimentally In this case, it isbest to perform a least squares curve fit to the data and then differentiate the resulting polynomial.For example, reconsider the example from the section on curve fitting (Section 10)
In the script below, the x and y data values determined by assignment statements and a seconddegree curve is fit to the data and plotted as the first subplot The derivative is approximatedfrom the data and then from the second degree curve fit and these curves are plotted as the secondsubplot Since diff computes the difference between elements of a vector, the resulting vectorcontains one less element than the original vector Thus, to plot the derivative, one element of the
x vector is discarded to form the vector xd The last element was discarded, so yd is a forwarddifference approximation
% Generate noisy data
title(’Noisy data and 2nd degree curve fit’),
legend(’Noisy data’,’2nd Degree Fit’,4)
% Differentiate noise data and fitted curve
legend(’Noisy data’,’2nd Degree Fit’,3)
The resulting plot is shown in Figure 11.10 Observing the approximation to the derivative shown in
Trang 8dashed lines in the bottom subplot, it is overwhelmingly apparent that approximating the derivative
by finite differences can lead to poor results Note that the derivative of the second order curve
fit shown in the solid curve in the bottom subplot does not show the large fluctuations of theapproximation
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
−2 0 2 4 6 8 10 12
Trang 9Grand total is 28 elements using 68 bytes
Trang 10ASCII Codes
Each character in a string is one element in an array that requires two bytes per character forstorage, using the ASCII code This differs from the eight bytes per element required for numerical
or double arrays The ASCII codes for the letters ‘A’ to ‘Z’ are the consecutive integers from 65
to 90, while the codes for ‘a’ to ‘z’ are 97 to 122 The function abs returns the ASCII codes for astring
>> text = ’This is a character string’
This is a character string
The relationship between strings and their ASCII codes allow you to do the following:
>> alpha = abs(’a’):abs(’z’);
>> disp(char(alpha))
abcdefghijklmnopqrstuvwxyz
Strings are Arrays
Since strings are arrays, they can be manipulated with array manipulation tools:
>> text = ’This is a character string’;
Trang 11>> v = [’Character strings having more than’
’one row must have the same number ’
’of columns - just like matrices ’]
v =
Character strings having more than
one row must have the same number
of columns - just like matrices
char(x) Converts the array x that contains positive integers representing
character codes into a character array (the first 127 codes are ASCII)
The result for any elements of x outside the range from 0 to 65535
is not defined
int2str(x) Rounds the elements of the matrix x to integers and converts the
result into a string matrix
num2str(x) Converts the matrix x into a string representation with about 4 digits
and an exponent if required This is useful for labeling plots withthe title, xlabel, ylabel, and text commands
str2num(s) Converts the string s, which should be an ASCII character
repre-sentation of a numeric value, to numeric reprerepre-sentation The stringmay contain digits, a decimal point, a leading + or - sign, an ’e’
preceeding a power of 10 scale factor, and an ’i’ for a complex unit
The num2str function can be used to convert numerical results into strings for use in formatingdisplayed results with disp For example, consider the following portion of a script:
tg = 2.2774;
xg = 144.6364;
disp([’time of flight: ’ num2str(tg) ’ s’])
disp([’distance traveled : ’ num2str(xg) ’ ft’])
The arguments for each of the disp commands are vectors of strings, with the first element being
a label, the second being a number converted to a string, and the third being the units of the
Trang 12quantity The label, the numerical results, and the units are displayed on one line, which was notpossible with other forms of the use of disp:
time of flight: 2.2774 s
distance traveled: 144.6364 ft
Trang 13String Functions
blanks(n) Returns a string of n blanks Used with disp, eg disp
([’xxx’ blanks(20) ’yyy’]) disp(blanks(n)’) movesthe cursor down n lines
deblank(s) Removes trailing blanks from string s
eval(s) Execute the string s as a Matlab expression or statement.eval(s1,s2) Provides the ability to catch errors Executes string s1 and
returns if the operation was successful If the operation erates an error, string s2 is evaluated before returning Thiscan be thought of as eval(’try’,’catch’)
gen-findstr(s1,s2) Find one string within another Returns the starting indices
of any occurrences of the shorter of the two strings in thelonger
ischar(s) Returns 1 if s is a character array and 0 otherwise
isletter(s) Returns 1 for each element of character array s containing
letters of the alphabet and 0 otherwise
isspace(s) Returns 1 for each element of character s containing white
space characters and 0 otherwise White space charactersare spaces, newlines, carriage returns, tabs, vertical tabs, andformfeeds
lasterr Returns a string containing the last error message issued
lasterr is usually used in conjunction with the two argumentform of eval: eval(’try’,’catch’) The ’catch’ action canexamine the lasterr string to determine the cause of theerror and take appropriate action
lower(s) Converts any uppercase characters in string s to the
corre-sponding lowercase character and leaves all other charactersunchanged
strcat(s1,s2,s3, ) Horizontally concatenates corresponding rows of the
charac-ter arrays s1, s2, s3 etc The trailing padding is ignored Allthe inputs must have the same number of rows (or any can
be a single string) When the inputs are all character arrays,the output is also a character array
strcmp(s1,s2) Returns 1 if strings s1 and s2 are identical and 0 otherwise.strjust(s) Returns a right justified version of the character array s.strmatch(str,strs) Searches through the rows of the character array of strings
strs to find strings that begin with string str, returning thematching row indices
strncmp(s1,s2,n) Returns 1 if the first n characters of the strings s1 and s2 are
identical and 0 otherwise
strrep(s1,s2,s3) Replaces all occurrences of the string s2 in string s1 with the
string s3 The new string is returned
upper(s) Converts any lower case characters in s to the
correspond-ing upper case character and leaves all other characters changed
Trang 14un-12.2 Time Computations
Current Date and Time
Three formats are supported for dates:
clock Returns a six element date vector vector containing the current
time and date in decimal form: [year month day hour minute
seconds] The first five elements are integers The seconds element
is accurate to several digits beyond the decimal point
date Returns a string containing the date in dd-mmm-yyyy format
now Returns the current date and time as a serial date number
The date number can be converted to a string with the datestr function:
datestr(d,dateform): Converts a data number d (such as that returned by now) into a datestring The string is formatted according to the format number dateform (see table below) Bydefault, dateform is 1, 16, or 0 depending on whether d contains dates, times or both
Trang 15dateform Date format Example
The function datenum is used to compute a date number It has three forms:
datenum(s): Returns the date number corresponding to the date string s
datenum(year,month,day): Returns the date number corresponding to the specified year, month,and day
datenum(year,month,day,hour minute,second): Returns the date number corresponding to thespecified year, month, day, hour, minute, and second
Trang 16A calendar can be generated for a desired month, for display in the Command window or to be
placed in a 6-by-7 array
Trang 1712.3 Base Conversions and Bit Operations
Base Conversion
Matlab provides functions for converting decimal numbers to other bases in the form of characterstrings These conversion functions include:
dec2bin(d) Returns the binary representation of d as a string d must be a
non-negative integer smaller than 252.
dec2bin(d,N) Produces a binary representation with at least N bits
bin2dec(b) Interprets the binary string b and returns the equivalent decimal
number
dec2hex(d) Returns the hexadecimal representation of decimal integer d as a
string d must be a non-negative integer smaller than 252.
hex2dec(h) Interprets the hexadecimal string h and returns the equivalent
dec-imal number If h is a character array, each row is interpreted as ahexadecimal string
dec2base(d,b) Returns the representation of d as a string in base b d must be
a non-negative integer smaller than 252 and b must be an integer
Trang 18>> b = dec2hex(30) % hex representation of 30
c = bitand(a,b) Returns the bit-wise AND of the two arguments a and b
c = bitor(a,b) Returns the bit-wise OR of the two arguments a and b
c = bitxor(a,b) Returns the bit-wise exclusive OR of the two arguments a and b
c = bitcmp(a,N) Returns the bit-wise complement of a as an N-bit non-negative
inte-ger
c = bitset(a,bit,v) Sets the bit at position bit to the value v, where v must be either 0
or 1
c = bitget(a,bit) Returns the value of the bit at position bit in a a must contain
non-negative integers and bit must be a number between 1 and thenumber of bits in a floating point integer (52for IEEE machines)
c = bitshift(a,N) Returns the value of a shifted by N bits If N > 0, this is same as
a multiplication by 2N (left shift) If N < 0, this is the same as a
division by 2^(-N) (right shift)
Examples of the use of these functions are best understood by displaying the results of each ation by dec2bin:
Trang 20Section 13
Symbolic Processing
We have focused on the use ofMatlab to perform numerical operations, involving numerical datarepresented by double precision floating point numbers We also given some consideration to themanipulation of text, represented by character strings In this section, we introduce the use of
Matlab to perform symbolic processing to manipulate mathematical expressions, in much the way
that we do with pencil and paper
The objective of symbolic processing is to obtain what are known as closed form solutions,
ex-pressions that don’t need to be iterated or updated in order to obtain answers An understanding
of these solutions often provides better physical and mathematical insight into the problem underinvestigation
For more information, type help symbolic inMatlab A tutorial demonstration is available withthe command symintro
The following notes represent a short introduction to the symbolic processing capabilities oflab
Mat-13.1 Symbolic Expressions and Algebra
To introduce symbolic processing, first consider the handling of symbolic expressions and the nipulation of algebra
ma-Declaring Symbolic Variables and Constants
To enable symbolic processing, the variables and constants involved must first be declared as
symbolic objects.
For example, to create the symbolic variables with names x and y:
>> syms x y