470 likes | 493 Views
AN ENGINEER’S GUIDE TO MATLAB 3rd Edition CHAPTER 3 DATA INPUT/OUTPUT. Chapter 3 – Objectives Present the means of displaying annotated numerical results in the MATLAB command window and the means of storing and retrieving data from files. Introduce cell arrays. Topics.
E N D
AN ENGINEER’S GUIDE TO MATLAB 3rd Edition CHAPTER 3 DATA INPUT/OUTPUT
Chapter 3 – Objectives • Present the means of displaying annotated numerical results in the MATLAB command window and the means of storing and retrieving data from files. • Introduce cell arrays.
Topics • Strings and Annotated Output • Creating Strings • Converting Numerical Values to Strings and Displaying Them • Entering Data With Input • Scalar, Vector, Matrix,and String • Input/Output Data Files • Cell Arrays • Input Microsoft Excel Files
Strings (Literals) - • Collections of any combination of letters, numbers, and special characters • Created, stored, and manipulated in arrays and defined similar to that for vectors and matrices • Differ from an array of numerical values in that – • Each character occupies one element in an array • Defined by enclosing all its characters between a pair of single quotes (' … ') • Typically used for – • Displaying information to the command window • Annotating data displayed to the command window • Annotating graphs
Examples – • Let s be the string testing123. The MATLAB syntax is • s = 'testing123' or s = ['testing123'] • To retrieve specific characters in the string s, we can use expressions like • s(7) g • s(3:6) stin • Strings can also be concatenated (added to form a longer string) as • sc = ['testing123', 'testing123'] • which produces the (120) string • sc = • testing123testing123
But, • sc = ['testing123'; 'testing123'] • creates the (210) matrix • scs = • testing123 • testing123 • Thus, • scs(1,:) testing123 • scs(2,:) testing123
One can find the starting locations of strings within strings using • findstr(string1, string2) • which searches the longer of the two strings for the occurrences of the shorter of the two strings. • Let us find the occurrences of ‘123’ in the concatenated string shown in the script below • sc = ['testing123', 'testing123'] • Loc=findstr(sc, '123') • Upon execution, we obtain • sc = • testing123testing123 • Loc = • 8 18
If we place a string in each row of a matrix, we have a convenient way in which to access string expressions. • The requirement is that each row must contain the same number of characters. • This requirement can be met by employing blanks to pad the rest of the string when the individual string expressions are of unequal length. • Thus, if we have the expression • lab = ['first';'last ';'middle'] • then • lab(1,: ) firstb • lab(2,: ) lastbb • lab(3,: ) middle • and b indicates a blank space.
The padding is performed by • char • Thus, the above expression can be replaced by the easier-to-use expression • lab = char('first','last','middle') • ord = size(lab) • which, when executed, displays • lab = • first • last • middle • ord = • 3 6 • The trailing blanks can be removed with • deblank
The leading and trailing blanks can be removed with • strtrim(s) • where s is a string. • Two strings can be compared by using • L = strcmp(A, B) • where A and B are strings and • L = 1 (true) if A = B • L = 0 (false) if AB • This function is intended to compare character data.
Example – • In the two strings defined in the script, A has two additional leading blanks and two additional trailing blanks than string B. • A = ' Yes and No '; • B = ' Yes and No '; • C1 = strcmp(A, B) • C2 = strcmp(strtrim(A), strtrim(B)) • which, upon execution, gives • C1 = • 0 • C2 = • 1
Converting Numerical Values to Strings and Displaying Them • To convert a numerical value to a string, we use • z = num2str(num) or z = num2str(num,N) • where • z is a string • num is either a number, an array of numbers, or an expression resulting in a number or an array of numbers • N is number of digits to be displayed (if omitted, N = 5)
Example - • Let a = 1000 = 3141.592653589. Then the various values of N will display the digits shown below. • num2str(a,1) 3e+003 • num2str(a,3) 3.14e+003 • num2str(a,4) 3142 • num2str(a,5) 3141.5 • num2str(a,8) 3141.5927 • Notice that the decimal point (.) does not count as a digit.
Example - • Let a = /1000 = 0.003141592653589. Then the various values of N will display the digits shown below • num2str(a,1) 0.003 • num2str(a,3) 0.00314 • num2str(a,4) 0.003142 • num2str(a,5) 0.0031416 • num2str(a,8) 0.0031415927
To convert an integer to a string, we use • z = int2str(num) • where num is an integer. If num is not an integer, then it is rounded to one.
Note: At least one blank space on each side of num2str is required. • A typical construct is to use num2str to concatenate the converted numerical value with some identifying text. • Thus, if num is, say, the weight in kilograms, and it is to be identified as such, then to display it to the command window we use disp as follows: • num = 12.567; • disp(['Product weight = ' num2str(num) ' kg']) • Upon execution, we obtain • Product weight = 12.567 kg
Let num be a vector of the lengths of the object. • Then, the script that displays a vector of values is • num = [12.567, 3.458, 9.111]; • disp(['Object length = ' num2str(num) ' m']) • Upon execution, we obtain • Object length = 12.567 3.458 9.111 m
To create annotation that accompanies each value of num, we use repmat as follows. • num = [12.567, 3.458, 9.111]; • n = length(num); % Let MATLAB do the counting • disp([repmat('Object length = ', n, 1) • num2str(num') repmat(' m', n, 1)]) • which, upon execution, displays • Object length = 12.567 m • Object length = 3.458 m • Object length = 9.111 m
An alternative way to display formatted data to the MATLAB command window is with • fprintf(1,'%…', variables) • where • ‘1’ indicates that the output goes to the command window • '%….' is the format specification pertaining to variables • % precedes each specific format specification, which is of the form • x.yq • where • q specifies the format • x specifies the minimum number of digits to be displayed • y is the number of digits to the right of the decimal point
Example – • We select q = f, which is a fixed point format, and use it to display the vector • num = [12, -14, 3098.458, 0.11167]; • several different ways. • To display this vector on one line, we have • num = [12, -14, 3098.458, 0.11167]; • fprintf(1,'%5.2f ', num) • which results in • 12.00 -14.00 3098.46 0.11
To display these values as a column of four numbers, we use the delimiter \n as follows: • num = [12 -14 3098.458 0.11167]; • fprintf(1,'%5.2f\n', num) • which, when executed, displays • 12.00 • -14.00 • 3098.46 • 0.11
To display each number with the appropriate number of digits, annotate each value, and print it in column form, we use • num = [12, -14, 3098.458, 0.11167]; • fprintf(1,'weight = %2.0f kg\npressure = %2.0f kPa\ntime = %5.3f s\nlength = %5.5f m', num) • The execution of this script results in • weight = 12 kg • pressure = -14 kPa • time = 3098.458 s • length = 0.11167 m
num2str can also employ the format specifications of fprintf by replacing the second argument N in num2str with a string format specification. • Suppose that we wanted to display a very small number as 0 instead of in exponent form. • If this number were x = 0.00045, then the script is • x = 0.00045; • disp(['x = ' num2str(x,'%2.1f')]) • displays • x = 0.0
Entering Data with input • Entering a Scalar – • To input a single numerical quantity, we use • InputData=input('Enter temperature in degrees C:'); • Upon execution, we have displayed in the command window • Enter temperature in degrees C: 121.7 • where the number 121.7 was entered by the user. • The semicolon at the end of the expression in the script suppresses the echoing of the value entered. • The variable InputData has the value of 121.7 after Enter is depressed.
One can also modify user-entered values in the same expression. • Consider the conversion of degrees to radians. Here • InputData = input('Enter the starting angle in • degrees: ')*pi/180; • When executed, we have in the command window • Enter the starting angle in degrees: 45 • where the value 45 was entered by the user. • However, the value of InputData is 0.7854 (= 45/180).
Entering a String – • To input a single string quantity, we append an 's' at the end of the input function • InputData = input('Enter file name, including its • extension: ','s'); • which displays command to the window. • Enter file name, including its extension: DataSet3.txt • where the string DataSet3.txt was entered by the user. Notice that no single quotation marks are required. The value of InputData is the string DataSet3.txt, which is a vector of length 12.
Entering a Vector – • To input a vector of numerical values, we use • InputData = input('Enter four temperatures in • degrees C: '); • which, upon execution, displays • Enter four temperatures in degrees C: [120, 141,169, 201] • where the vector of numbers [120, 141, 169, 201] was entered by the user. The square brackets are required. • If a column vector was required, then the user's response would be either • [120, 141, 169, 201]' or [120; 141; 169; 201]
Entering a Matrix - • To input a matrix of numerical values, we use • InputData = input('Enter three temperatures in • degrees C\nfor levels 1 and 2:'); • which displays • Enter the three temperatures in degrees C • for levels 1 and 2: [67, 35, 91; 44, 51, 103] • where the array [67, 35, 91; 44, 51, 103] was entered by the user. • The variable InputData is a (23) array.
Input/Output Data Files – load/save • load • Reads data on a row-by-row basis. • Each row separated by an Enter, where Enter is used instead of the semicolon. • Each data value separated by either one or more blanks or by a comma. • The number of columns of data in each row must be the same. • For a row vector, data entered without using Enter. • For a column vector, each data value followed by an • Enter.
Example – • Assume that data reside in an ASCII text file DataSection33.txt in the form • 11 12 13 • 21 22 23 • 31 32 33 • 41 42 43 • The load function is • load('DataSection33.txt')
Let us square each element of the matrix in DataSection33.txt. The script is • load('DataSection33.txt') • y = DataSection33.^2 • which, upon execution, results in • y = • 121 144 169 • 441 484 529 • 961 1024 1089 • 1681 1764 1849 11 12 13 21 22 23 31 32 33 41 42 43
If one wanted to operate on data in different files, each having a different file name, then we have to employ a different technique. • Here, the user will enter the file name when requested to do so and, as before, the script will square the data residing in the file whose name is specified when the script is executed. The script is • FileName1 = input('Enter file name containing data • (including suffix): ','s'); • load(FileName1); • m = findstr(FileName1,'.'); • data1 = eval(FileName1(1:m-1)); • y = data1.^2
Since FileName1 is still unknown to the remaining expressions in the script, it must be converted to a numerical quantity. This is done by the eval function, which evaluates the string quantity appearing in its argument.
save • If one wants to save numerical values resulting from the execution of a script or function to a file, then we use • save('File name', 'Variable 1', 'Variable 2', …, '-ascii') • where • 'File name' is a string containing the name of the file to be saved and its directory, if other that the current directory. • 'Variable n' are strings containing the names of the n variables that are to be saved in the order that they appear. • '-ascii' is a string indicating that the data will be saved in ascii format.
Example – • Save the square of each value in a file named DataSection33.txt as ASCII text. The script is • load('DataSection33.txt') • y = DataSection33.^2; • save('SavedDataSection33.txt', 'y', '-ascii') • Upon execution, the script creates a text file whose contents are • 1.2100000e+002 1.4400000e+002 1.6900000e+002 • 4.4100000e+002 4.8400000e+002 5.2900000e+002 • 9.6100000e+002 1.0240000e+003 1.0890000e+003 • 1.6810000e+003 1.7640000e+003 1.8490000e+003
A Note About Path Name – • When just the file name is given, MATLAB places the file in the current directory. • In order to place the file in a specific directory, the entire path name must be given. • For example, • load('DataSection33.txt') % File in current directory • y = DataSection33.^2; • z = sqrt(Datasection33); • save('c:\Matlab mfiles\Matlab • results\SavedDataSection33.txt', 'y', ‘z', '-ascii')
Execution of this script creates the file SavedDataSection331.txt with the contents • 1.2100000e+002 1.4400000e+002 1.6900000e+002 • 4.4100000e+002 4.8400000e+002 5.2900000e+002 • 9.6100000e+002 1.0240000e+003 1.0890000e+003 • 1.6810000e+003 1.7640000e+003 1.8490000e+003 • 3.3166248e+000 3.4641016e+000 3.6055513e+000 • 4.5825757e+000 4.6904158e+000 4.7958315e+000 • 5.5677644e+000 5.6568542e+000 5.7445626e+000 • 6.4031242e+000 6.4807407e+000 6.5574385e+000 y z
Cell Arrays – • Cell arrays are a special class of arrays whose elements consist of cells that themselves contain arrays. • They provide a hierarchical way of storing dissimilar kinds of data. • Any cell in a cell array can be accessed through matrix indexing as is done with standard vectors and matrices. • Cell notation differs from standard matrix notation in that open braces ‘{’ and the closed braces ‘}’ are used instead of open ‘[’ and closed ‘]’ brackets.
Example – • Let us create four different arrays of data as shown in the following script • A = ones(3,2) • B = magic(3) • C = char('Pressure', 'Temperature', 'Displacement') • D = [6+7j, 15] • Upon executing this script, we obtain
A = 1 1 1 1 1 1 B = 8 1 6 3 5 7 4 9 2 C = Pressure Temperature Displacement D = 6.0000 + 7.0000i 15.0000
We now add to this script the cell assignment statement to create a (22) cell array, which is analogous to that used for standard arrays, except that we use braces as delimiters. Thus, • A = ones(3,2); • B = magic(3); • C = char('Pressure', 'Temperature', 'Displacement'); • D = [6+7j, 15]; • Cel = {A, B; C, D} • After executing this script, we obtain • Cel = • [3x2 double] [3x3 double] • [3x12 char ] [1x2 double]
Notice that we do not get what is specifically in each cell, only what the size of the data arrays in each cell are and their type. • To display the contents of Cel to the command window, we use • celldisp(x) • Then, the program becomes • A = ones(3,2); • B = magic(3); • C = char('Pressure', 'Temperature', 'Displacement'); • D = [6+7j, 15]; • Cel = {A, B; C, D}; • celldisp(Cel)
which, upon execution, gives • Cel{1,1} = • 1 1 • 1 1 • 1 1 • Cel{2,1} = • Pressure • Temperature • Displacement • Cel{1,2} = • 8 1 6 • 3 5 7 • 4 9 2 • Cel{2,2} = • 6.0000 + 7.0000i 15.0000
To access each cell individually, we use the index notation used for standard array variables, except that we use braces instead of parentheses. Thus, • A = ones(3,2); • B = magic(3); • C = char('Pressure', 'Temperature', 'Displacement'); • D = [6+7j,15]; • Cel = {A, B; C, D}; • Cell_1_2 = Cel{1,2} • which, upon execution, gives • Cell_1_2 = • 8 1 6 • 3 5 7 • 4 9 2
With cell arrays, the use of sort can be extended to sort words in dictionary order. • Consider the following script, where we will create a cell array of five words and then sort them. • Words = {'application', 'apple', 'friend', 'apply', 'fiend'}; • WordSort = sort(Words)' • The execution of this script gives • 'apple' • 'application' • 'apply' • 'fiend' • 'friend'
Input Microsoft Excel Files • Data files created in Microsoft Excel can be read into MATLAB with the function • [X, Y] = xlsread('Filename') • where X will be an array containing the columns and rows of data and Y will be a cell array containing any text headers that accompany the data. • The file name must contain the suffix ‘.xls’.
Example – • Consider the data generated in Excel shown below and saved in ForceDispData.xls. • The script to read this file is • [X, Y] = xlsread('ForceDispData.xls') X = 100.0000 0.1000 110.0000 0.2000 135.0000 0.3300 150.0000 0.4000 175.0000 0.5500 Y = [1x20 char] [] 'Force' 'Displacement' '(kPa)' '(mm)' Note: Y is a (3×2) cell array: Y{1,1}=Transducer Linearity