Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

8 - Chapman MATLAB Programming for Engineers

.pdf
Скачиваний:
91
Добавлен:
12.03.2015
Размер:
1.97 Mб
Скачать

Thus, we observe that the approximation is converging to the correct result.

Since the Matlab diff function returns only an approximate derivative, it is necessary to use the resolution required to achieve the accuracy desired.

Di erentiation Error Sensitivity

Di erentiation is sensitive to minor changes in the shape of a function, as any small change in the function can easily create large changes in its slope in the neighborhood of the change.

Because of this inherent sensitivity in di erentiation, numerical di erentiation is avoided whenever possible, especially if the data to be di erentiated are obtained experimentally. In this case, it is best to perform a least squares curve fit to the data and then di erentiate 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 second degree curve is fit to the data and plotted as the first subplot. The derivative is approximated from the data and then from the second degree curve fit and these curves are plotted as the second subplot. Since diff computes the di erence between elements of a vector, the resulting vector contains 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 forward di erence approximation.

%Generate noisy data x = 0:0.1:1;

y = [-0.447 1.978 3.28 6.16 7.08 7.34 7.66 9.56 9.48 9.30 11.2];

%2nd degree curve fit

a = polyfit(x,y,2);

xi = linspace(0,1,101); yi = polyval(a,xi);

subplot(2,1,1),plot(x,y,’--o’,xi,yi),...

xlabel(’x’), ylabel(’y’),...

title(’Noisy data and 2nd degree curve fit’),...

legend(’Noisy data’,’2nd Degree Fit’,4)

% Differentiate noise data and fitted curve yd = diff(y)./diff(x);

ad = polyder(a);

yid = polyval(ad,xi); xd = x(1:end-1);

subplot(2,1,2),plot(xd,yd,’--o’,xi,yid),...

xlabel(’x’), ylabel(’dy/dx’),...

title(’Derivative approximations’),...

legend(’Noisy data’,’2nd Degree Fit’,3)

The resulting plot is shown in Figure 11.10. Observing the approximation to the derivative shown in

237

dashed lines in the bottom subplot, it is overwhelmingly apparent that approximating the derivative by finite di erences 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 the approximation.

Noisy data and 2nd degree curve fit

12

 

 

 

 

 

 

 

 

 

 

10

 

 

 

 

 

 

 

 

 

 

8

 

 

 

 

 

 

 

 

 

 

6

 

 

 

 

 

 

 

 

 

 

y

 

 

 

 

 

 

 

 

 

 

4

 

 

 

 

 

 

 

 

 

 

2

 

 

 

 

 

 

 

 

 

 

0

 

 

 

 

 

 

 

 

 

 

−2

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

0

 

 

 

 

 

x

 

 

 

 

 

Derivative approximations

 

30

 

 

 

 

 

 

 

 

 

 

 

25

 

 

 

 

 

 

 

 

 

 

 

20

 

 

 

 

 

 

 

 

 

 

dy/dx

15

 

 

 

 

 

 

 

 

 

 

10

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

5

 

 

 

 

 

 

 

 

 

 

 

0

 

 

 

 

 

 

 

 

 

 

 

−5

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

 

0

 

 

 

 

 

 

x

 

 

 

 

 

Figure 11.10: Curve fitting and derivative approximation

238

Section 12

Strings, Time, Base Conversion and

Bit Operations

12.1Character Strings

While Matlab is primarily intended for number crunching, there are times when it is desirable to manipulate text, as is needed in placing labels and titles on plots. In Matlab, text is referred to as character strings or simply strings.

String Construction

Character strings in Matlab are special numerical arrays of ASCII values that are displayed as their character string representation. For example:

>>text = ’This is a character string’ text =

This is a character string

>>size(text)

ans =

126

>>whos

Name

Size

Bytes

Class

ans

1x2

16

double array

text

1x26

52

char array

Grand total is 28 elements using 68 bytes

239

ASCII Codes

Each character in a string is one element in an array that requires two bytes per character for storage, using the ASCII code. This di ers 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 a string.

>>text = ’This is a character string’ text =

This is a character string

>>d = abs(text)

d=

Columns 1 through 12

84

104

105

115

32

105

115

32

97

32

99

104

Columns 13 through

24

 

 

 

 

 

 

 

 

97

114

97

99

116

101

114

32

115

116

114

105

Columns 25

through

26

 

 

 

 

 

 

 

 

110

103

 

 

 

 

 

 

 

 

 

 

The function char performs the inverse transformation, from ASCII codes to a string:

>> char(d) ans =

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’;

>>u = text(11:19)

u = character

As with matrices, character strings can have multiple rows, but each row must have an equal number of columns. Therefore, blanks are explicitly required to make all rows the same length. For example:

240

>> 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

 

>> size(v)

 

 

 

ans =

 

 

 

 

3

34

 

 

 

Concatenation of Strings

Because strings are arrays, they may be concatenated (joined) with square brackets. For example:

>>today = ’May’;

>>today = [today, ’ 18’] today =

May 18

String Conversions

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 with the title, xlabel, ylabel, and text commands.

str2num(s) Converts the string s, which should be an ASCII character representation of a numeric value, to numeric representation. The string may 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 formating displayed 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

241

quantity. The label, the numerical results, and the units are displayed on one line, which was not possible with other forms of the use of disp:

time of flight: 2.2774 s distance traveled: 144.6364 ft

242

String Functions

blanks(n)

Returns a string of n blanks.

Used with disp, eg. disp

 

([’xxx’ blanks(20) ’yyy’]).

disp(blanks(n)’) moves

 

the 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 gen-

 

erates an error, string s2 is evaluated before returning. This

 

can be thought of as eval(’try’,’catch’).

findstr(s1,s2)

Find one string within another. Returns the starting indices

 

of any occurrences of the shorter of the two strings in the

 

longer.

 

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 characters

 

are spaces, newlines, carriage returns, tabs, vertical tabs, and

 

formfeeds.

 

lasterr

Returns a string containing the last error message issued.

 

lasterr is usually used in conjunction with the two argument

 

form of eval: eval(’try’,’catch’). The ’catch’ action can

 

examine the lasterr string to determine the cause of the

 

error and take appropriate action.

lower(s)

Converts any uppercase characters in string s to the corre-

 

sponding lowercase character and leaves all other characters

 

unchanged.

 

strcat(s1,s2,s3,...) Horizontally concatenates corresponding rows of the charac-

 

ter arrays s1, s2, s3 etc. The trailing padding is ignored. All

 

the 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 the

 

matching 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 un-

 

changed.

243

12.2Time 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.

Examples:

>> t = clock t =

1998

6

10

10

18

59.57

>>date ans = 10-Jun-1998

>>format long

>>d = now

d =

7.299164376449074e+005

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 date string. The string is formatted according to the format number dateform (see table below). By default, dateform is 1, 16, or 0 depending on whether d contains dates, times or both.

244

dateform

Date format

Example

0

’dd-mmm-yyyy HH:MM:SS’

01-Mar-1995 15:45:17

2

’mm/dd/yy’

03/01/95

3

’mmm’

Mar

4

’m’

M

5

’mm’

3

6

’mm/dd’

03/01

7

’dd’

1

8

’ddd’

Wed

9

’d’

W

10

’yyyy’

1995

11

’yy’

95

12

’mmmyy’

Mar95

13

’HH:MM:SS’

15:45:17

14

’HH:MM:SS PM’

3:45:17 PM

15

’HH:MM’

15:45

16

’HH:MM PM’

3:45 PM

17

’QQ-YY’

Q1-96

18

’QQ’

Q1

Examples:

>>ds = datestr(d) ds =

10-Jun-1998 10:30:13

>>datestr(d,14)

ans = 10:30:13 AM

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 the specified year, month, day, hour, minute, and second.

Examples:

>>datenum(ds) ans =

7.299164376504630e+005

>>datenum(1998,6,13)

ans =

729919

245

>> datenum(1998,6,16,10,30,00)

ans = 7.299224375000000e+005

Date Functions

The day of the week may be found from a date string or a date number using weekday, using the convention that Sunday = 1 and Saturday = 7.

>> [d s] = weekday(’9/9/90’) d =

1

s = Sun

A calendar can be generated for a desired month, for display in the Command window or to be placed in a 6-by-7 array.

>> calendar(’9/9/90’)

 

 

 

 

 

 

Sep 1990

 

 

 

S

M

Tu

W

Th

F

S

0

0

0

0

0

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

0

0

0

0

0

0

>> a = calendar(1978,6)

 

 

 

a =

 

 

 

 

 

 

0

0

0

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

0

0

0

0

0

0

0

0

Timing Functions

The functions tic and toc are used to time a sequence of commands. tic starts the timer; toc stops the timer and displays the elapsed time in seconds.

Example:

tic

246

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]