Chapter 4

Using Script Files and Managing Data

A script file (see Section 1.8) is a list of MATLAB commands, called a program, that is saved in a file. When the script file is executed (run), MATLAB executes the commands. Section 1.8 describes how to create, save, and run a simple script file in which the commands are executed in the order in which they are listed, and in which all the variables are defined within the script file. This chapter gives more details about how to input data to a script file, how data is stored in MATLAB, various ways to display and save data that is created in script files, and how to exchange data between MATLAB and other applications. (How to write more advanced programs in which commands are not necessarily executed in a simple order is covered in Chapter 6.)

In general, variables can be defined (created) in several ways. As shown in Chapter 2, variables can be defined implicitly by assigning values to a variable name. Variables can also be assigned values by the output of a function. In addition, variables can be defined with data that is imported from files outside MATLAB. Once defined (either in the Command Window or when a script file is executed), the variables are stored in MATLAB’s Workspace.

Variables that reside in the workspace can be displayed in various ways, saved, or exported to applications outside MATLAB. Similarly, data from files outside MATLAB can be imported to the workspace and then used in MATLAB.

Section 4.1 explains how MATLAB stores data in the workspace and how the user can see the data that is stored. Section 4.2 shows how variables that are used in script files can be defined in the Command Window and/or in script files. Section 4.3 shows how to output data that is generated when script files are executed. Section 4.4 explains how the variables in the workspace can be saved and then retrieved, and Section 4.5 shows how to import and export data from and to applications outside MATLAB.

4.1  THE MATLAB WORKSPACE AND THE WORKSPACE WINDOW

The MATLAB workspace consists of the set of variables (named arrays) that are defined and stored during a MATLAB session. It includes variables that have been defined in the Command Window and variables defined when script files are executed. This means that the Command Window and script files share the same memory zone within the computer. This implies that once a variable is in the workspace, it is recognized and can be used, and it can be reassigned new values, in both the Command Window and script files. As will be explained in Chapter 7 (Section 7.3), there is another type of file in MATLAB, called a function file, where variables can also be defined. These variables, however, are normally not shared with other parts of the program since they use a separate workspace.

Recall from Chapter 1 that the who command displays a list of the variables currently in the workspace. The whos command displays a list of the variables currently in the workspace and information about their size, bytes, and class. An example is shown below.

images

The variables currently in memory can also be viewed in the Workspace Window. This window can be opened by selecting Workspace in the Desktop menu. Figure 4-1 shows the Workspace Window that corresponds to the variables defined above. The variables that are displayed in the Workspace Window can also be edited (changed). Double-clicking on a variable opens the Variable Editor Window, where the content of the variable is displayed in a table. For example, Figure 4-2 shows the Variable Editor Window that opens when the variable g in Figure 4-1 is double-clicked.

images

Figure 4-1:  The Workspace Window.

images

Figure 4-2:  The Variable Editor Window.

The elements in the Variable Editor Window can be edited. The variables in the Workspace Window can be deleted by selecting them, and then either pressing the delete key on the keyboard or selecting delete from the edit menu. This has the same effect as entering the command clear variable_name in the Command Window.

4.2  INPUT TO A SCRIPT FILE

When a script file is executed, the variables that are used in the calculations within the file must have assigned values. In other words, the variables must be in the workspace. The assignment of a value to a variable can be done in three ways, depending on where and how the variable is defined.

1. The variable is defined and assigned a value in the script file.

In this case the assignment of a value to the variable is part of the script file. If the user wants to run the file with a different variable value, the file must be edited and the assignment of the variable changed. Then, after the file is saved, it can be executed again.

The following is an example of such a case. The script file (saved as Chapter4Example2) calculates the average points scored in three games.

images

The display in the Command Window when the script file is executed is:

images

2. The variable is defined and assigned a value in the Command Window.

In this case the assignment of a value to the variable is done in the Command Window. (Recall that the variable is recognized in the script file.) If the user wants to run the script file with a different value for the variable, the new value is assigned in the Command Window and the file is executed again.

For the previous example in which the script file has a program that calculates the avera2225ge of points scored in three games, the script file (saved as Chapter4Example3) is:

% This script file calculates the average points scored in three games.
% The assignment of the values of the points to the variables
% game1, game2, and game3 is done in the Command Window.

ave_points=(game1+game2+game3)/3

The Command Window for running this file is:

images

images

3. The variable is defined in the script file, but a specific value is entered in the Command Window when the script file is executed.

In this case the variable is defined in the script file, and when the file is executed, the user is prompted to assign a value to the variable in the Command Window. This is done by using the input command for creating the variable.

The form of the input command is:

images

When the input command is executed as the script file runs, the string is displayed in the Command Window. The string is a message prompting the user to enter a value that is assigned to the variable. The user types the value and presses the Enter key. This assigns the value to the variable. As with any variable, the variable and its assigned value will be displayed in the Command Window unless a semicolon is typed at the very end of the input command. A script file that uses the input command to enter the points scored in each game to the program that calculates the average of the scores is shown below.

% This script file calculates the average points scored in three games.
% The points from each game are assigned to the variables by
% using the input command.
game1=input('Enter the points scored in the first game ');
game2=input('Enter the points scored in the second game ');
game3=input('Enter the points scored in the third game ');
ave_points=(game1+game2+game3)/3;

The following shows the Command Window when this script file (saved as Chapter4Example4) is executed.

images

In this example scalars are assigned to the variables. In general, however, vectors and arrays can also be assigned. This is done by typing the array in the same way that it is usually assigned to a variable (left bracket, then typing row by row, and a right bracket).

The input command can also be used to assign a string to a variable. This can be done in one of two ways. One way is to use the command in the same form as shown above, and when the prompt message appears the string is typed between two single quotes in the same way that a string is assigned to a variable without the input command. The second way is to use an option in the input command that defines the characters that are entered as a string. The form of the command is:

images

where the ‘s’ inside the command defines the characters that will be entered as a string. In this case when the prompt message appears, the text is typed in without the single quotes, but it is assigned to the variable as a string. An example where the input command is used with this option is included in Sample Problem 6-4.

4.3  OUTPUT COMMANDS

As discussed before, MATLAB automatically generates a display when some commands are executed. For example, when a variable is assigned a value, or the name of a previously assigned variable is typed and the Enter key is pressed, MATLAB displays the variable and its value. This type of output is not displayed if a semicolon is typed at the end of the command. In addition to this automatic display, MATLAB has several commands that can be used to generate displays. The displays can be messages that provide information, numerical data, and plots. Two commands that are frequently used to generate output are disp and fprintf. The disp command displays the output on the screen, while the fprintf command can be used to display the output on the screen or to save the output to a file. The commands can be used in the Command Window, in a script file, and, as will be shown later, in a function file. When these commands are used in a script file, the display output that they generate is displayed in the Command Window.

4.3.1  The disp Command

The disp command is used to display the elements of a variable without displaying the name of the variable, and to display text. The format of the disp command is:

images

•   Every time the disp command is executed, the display it generates appears in a new line. One example is:

images

The next example shows the use of the disp command in the script file that calculates the average points scored in three games.

images

When this file (saved as Chapter4Example5) is executed, the display in the Command Window is:

images

•   Only one variable can be displayed in a disp command. If elements of two variables need to be displayed together, a new variable (that contains the elements to be displayed) must first be defined and then displayed.

In many situations it is nice to display output (numbers) in a table. This can be done by first defining a variable that is an array with the numbers and then using the disp command to display the array. Headings to the columns can also be created with the disp command. Since in the disp command the user cannot control the format (the width of the columns and the distance between the columns) of the display of the array, the position of the headings has to be aligned with the columns by adding spaces. As an example, the script file below shows how to display the population data from Chapter 2 in a table.

images

When this script file (saved as PopTable) is executed, the display in the Command Window is:

images

Another example of displaying a table is shown in Sample Problem 4-3. Tables can also be created and displayed with the fprintf command, which is explained in the next section.

4.3.2  The fprintf Command

The fprintf command can be used to display output (text and data) on the screen or to save it to a file. With this command (unlike with the disp command) the output can be formatted. For example, text and numerical values of variables can be intermixed and displayed in the same line. In addition, the format of the numbers can be controlled.

With many available options, the fprintf command can be long and complicated. To avoid confusion, the command is presented gradually. First, this section shows how to use the command to display text messages, then how to mix numerical data and text, next how to format the display of numbers, and finally how to save the output to a file.

Using the fprintf command to display text:

To display text, the fprintf command has the form:

images

For example:

fprintf('The problem, as entered, has no solution. Please check the
input data.')

If this line is part of a script file, then when the line is executed, the following is displayed in the Command Window:

The problem, as entered, has no solution. Please check the input data.

With the fprintf command it is possible to start a new line in the middle of the string. This is done by inserting before the character that will start the new line. For example, inserting after the first sentence in the previous example gives:

fprintf('The problem, as entered, has no solution. Please
check the input data.')

When this line executes, the display in the Command Window is:

The problem, as entered, has no solution.
Please check the input data.

The is called an escape character. It is used to control the display. Other escape characters that can be inserted within the string are:

 Backspace.
Horizontal tab.

When a program has more than one fprintf command, the display generated is continuous (the fprintf command does not automatically start a new line). This is true even if there are other commands between the fprintf commands. An example is the following script file:

fprintf('The problem, as entered, has no solution. Please check the
input data.')
x = 6; d = 19 + 5*x;
fprintf('Try to run the program later.')
y = d + x;
fprintf('Use different input values.')

When this file is executed the display in the Command Window is:

The problem, as entered, has no solution. Please check the
input data.Try to run the program later.Use different input
values.

To start a new line with the fprintf command, must be typed at the start of the string.

Using the fprintf command to display a mix of text and numerical data:

To display a mix of text and a number (value of a variable), the fprintf command has the form:

images

The formatting elements are:

images

The flag, which is optional, can be one of the following three characters:

Character used for flag Description
− (minus sign) Left-justifies the number within the field.
   + (plus sign) Prints a sign character (+ or −) in front of the number.
     0 (zero) Adds zeros if the number is shorter than the field.

The field width and precision (5.2 in the previous example) are optional. The first number (5 in the example) is the field width, which specifies the minimum number of digits in the display. If the number to be displayed is shorter than the field width, spaces or zeros are added in front of the number. The precision is the second number (2 in the example). It specifies the number of digits to be displayed to the right of the decimal point.

The last element in the formatting elements, which is required, is the conversion character, which specifies the notation in which the number is displayed. Some of the common notations are:

e Exponential notation using lowercase e (e.g., 1.709098e+001).
E Exponential notation using uppercase E (e.g., 1.709098E+001).
f Fixed-point notation (e.g., 17.090980).
g The shorter of e or f notations.
G The shorter of E or f notations.
i Integer.

Information about additional notation is available in the help menu of MATLAB. As an example, the fprintf command with a mix of text and a number is used in the script file that calculates the average points scored in three games.

% This script file calculates the average points scored in three games.
% The values are assigned to the variables by using the input command.
% The fprintf command is used to display the output.
game(1) = input('Enter the points scored in the first game    ');
game(2) = input('Enter the points scored in the second game   ');
game(3) = input('Enter the points scored in the third game    ');
ave_points = mean(game);

images

Notice that, besides using the fprintf command, this file differs from the ones shown earlier in the chapter in that the scores are stored in the first three elements of a vector named game, and the average of the scores is calculated by using the mean function. The Command Window where the script file above (saved as Chapter4Example6) was run is shown below.

images

With the fprintf command it is possible to insert more than one number (value of a variable) within the text. This is done by typing %g (or % followed by any formatting elements) at the places in the text where the numbers are to be inserted. Then, after the string argument of the command (following the comma), the names of the variables are typed in the order in which they are inserted in the text. In general the command looks like:

images

An example is shown in the following script file:

images

fprintf('A projectile shot at %3.2f degrees with a velocity
of %4.2f km/h will travel a distance of %g km. ',theta,v,d)

When this script file (saved as Chapter4Example7) is executed, the display in the Command Window is:

>> Chapter4Example7
A projectile shot at 30.00 degrees with a velocity of
1584.00 km/h will travel a distance of 17.091 km.
>>

Additional remarks about the fprintf command:

•   To place a single quotation mark in the displayed text, type two single quotation marks in the string inside the command.

•   The fprintf command is vectorized. This means that when a variable that is a vector or a matrix is included in the command, the command repeats itself until all the elements are displayed. If the variable is a matrix, the data is used column by column.

For example, the script file below creates a 2 × 5 matrix T in which the first row contains the numbers 1 through 5, and the second row shows the corresponding square roots.

images

When this script file is executed, the display in the Command Window is:

images

Using the fprintf command to save output to a file:

In addition to displaying output in the Command Window, the fprintf command can be used for writing the output to a file when it is necessary to save the output. The data that is saved can subsequently be displayed or used in MATLAB and in other applications.

Writing output to a file requires three steps:

a)  Opening a file using the fopen command.

b)  Writing the output to the open file using the fprintf command.

c)  Closing the file using the fclose command.

Step a:

Before data can be written to a file, the file must be opened. This is done with the fopen command, which creates a new file or opens an existing file. The fopen command has the form:

images

fid is a variable called the file identifier. A scalar value is assigned to fid when fopen is executed. The file name is written (including its extension) within single quotes as a string. The permission is a code (also written as a string) that tells how the file is opened. Some of the more common permission codes are:

‘r’ Open file for reading (default).
‘w’ Open file for writing. If the file already exists, its content is deleted.
If the file does not exist, a new file is created.
‘a’ Same as ‘w’, except that if the file exists the written data is appended to the end of the file.
‘r+’ Open (do not create) file for reading and writing.
‘w+’ Open file for reading and writing. If the file already exists, its content is deleted. If the file does not exist, a new file is created.
‘a+’ Same as ‘w+’, except that if the file exists the written data is appended to the end of the file.

If a permission code is not included in the command, the file opens with the default code ‘r’. Additional permission codes are described in the help menu.

Step b:

Once the file is open, the fprintf command can be used to write output to the file. The fprintf command is used in exactly the same way as it is used to display output in the Command Window, except that the variable fid is inserted inside the command. The fprintf command then has the form:

images

Step c:

When the writing of data to the file is complete, the file is closed using the fclose command. The fclose command has the form:

images

Additional notes on using the fprintf command for saving output to a file:

•   The created file is saved in the current directory.

•   It is possible to use the fprintf command to write to several different files. This is done by first opening the files, assigning a different fid to each (e.g. fid1, fid2, fid3, etc.), and then using the fid of a specific file in the fprintf command to write to that file.

An example of using fprintf commands for saving output to two files is shown in the following script file. The program in the file generates two unit conversion tables. One table converts velocity units from miles per hour to kilometers per hour, and the other table converts force units from pounds to newtons. Each conversion table is saved to a different text file (extension .txt).

images

When the script file above is executed two new .txt files, named VmphtoVkm and FlbtoFN, are created and saved in the current directory. These files can be opened with any application that can read .txt files. Figures 4-3 and 4-4 show how the two files appear when they are opened with Microsoft Word.

images

Figure 4-3:  The VmphtoVkm.txt file opened in Word.

images

Figure 4-4:  The FlbtoFN.txt file opened in Word.

4.4 THE save AND load COMMANDS

The save and load commands are most useful for saving and retrieving data for use in MATLAB. The save command can be used for saving the variables that are currently in the workspace, and the load command is used for retrieving variables that have been previously saved, to the workspace. The workspace can be saved when MATLAB is used in one type of platform (e.g., PC), and retrieved for use in MATLAB in another platform (e.g., Mac). The save and load commands can also be used for exchanging data with applications outside MATLAB. Additional commands that can be used for this purpose are presented in Section 4.5.

4.4.1  The save Command

The save command is used for saving the variables (all or some of them) that are stored in the workspace. The two simplest forms of the save command are:

images

When either one of these commands is executed, all of the variables currently in the workspace are saved in a file named file_name.mat that is created in the current directory. In mat files, which are written in a binary format, each variable preserves its name, type, size, and value. These files cannot be read by other applications. The save command can also be used for saving only some of the variables that are in the workspace. For example, to save two variables named var1 and var2, the command is:

images

The save command can also be used for saving in ASCII format, which can be read by applications outside MATLAB. Saving in ASCII format is done by adding the argument -ascii in the command (for example, save file_name-ascii). In the ASCII format the variable’s name, type, and size are not preserved. The data is saved as characters separated by spaces but without the variable names. For example, the following shows how two variables (a 1 × 4 vector and a 2 × 3 matrix) are defined in the Command Window and then saved in ASCII format to a file named DatSavAsci:

images

Once saved, the file can be opened by any application that can read ASCII files. For example, Figure 4-5 shows the data when the file is opened with Notepad.

images

Figure 4-5:  Data saved in ASCII format.

Note that the file does not include the names of the variables, just the numerical values of the variables (first A and then V) are listed.

4.4.2   The load Command

The load command can be used for retrieving variables that were saved with the save command back to the workspace, and for importing data that was created with other applications and saved in ASCII format or in text (.txt) files. Variables that were saved with the save command in .mat files can be retrieved with the command:

images

When the command is executed, all the variables in the file (with the name, type, size, and values as were saved) are added (loaded back) to the workspace. If the workspace already has a variable with the same name as a variable that is retrieved with the load command, then the variable that is retrieved replaces the existing variable. The load command can also be used for retrieving only some of the variables that are in the saved .mat file. For example, to retrieve two variables named var1 and var2, the command is:

images

The load command can also be used to import data that is saved in ASCII or text (.txt) to the workspace. This is possible, however, only if the data in the file is in the form of a variable in MATLAB. Thus, the file can have one number (scalar), a row or a column of numbers (vector), or rows with the same number of numbers in each (matrix). For example, the data shown in Figure 4-5 cannot be loaded with the load command (even though it was saved in ASCII format with the save command), because the number of elements is not the same in all rows. (Recall that this file was created by saving two different variables.)

When data is loaded from an ASCII or text file into the workspace, it has to be assigned to a variable name. Data in ASCII format can be loaded with either of the following two forms of the load command:

images

If the data is in a text file, the extension .txt has to be added to the file name. The form of the load command is then:

images

In the first form of the command the data is assigned to a variable that has the name of the file. In the second form the data is assigned to a variable named VarName.

For example, the data shown in Figure 4-6 (a 3 × 2 matrix) is typed in Notepad, and then saved as DataFromText.txt.

images

Figure 4-6:  Data saved as .txt file.

Next, two forms of the load command are used to import the data in the text file to the Workspace of MATLAB. In the first command the data is assigned to a variable named DfT. In the second command the data is automatically assigned to a variable named DataFromText, which is the name of the text file where the data was saved.

images

Importing data to (or exporting from) other applications can also be done, with MATLAB commands that are presented in the next section.

4.5  IMPORTING AND EXPORTING DATA

MATLAB is often used for analyzing data that was recorded in experiments or generated by other computer programs. This can be done by first importing the data into MATLAB. Similarly, data that is produced by MATLAB sometimes needs to be transferred to other computer applications. There are various types of data (numerical, text, audio, graphics, and images). This section describes only how to import and export numerical data, which is probably the most common type of data that needs to be transferred by new users of MATLAB. For other types of data transfer, look in the Help Window under File I/O.

Importing data can be done either by using commands or by using the Import Wizard. Commands are useful when the format of the data being imported is known. MATLAB has several commands that can be used for importing various types of data. Importing commands can also be included in a script file such that the data is imported when the script is executed. The Import Wizard is useful when the format of the data (or the command that is applicable for importing the data) is not known. The Import Wizard determines the format of the data and automatically imports it.

4.5.1  Commands for Importing and Exporting Data

This section describes—in detail—how to transfer data into and out of Excel spreadsheets. Microsoft Excel is commonly used for storing data, and Excel is compatible with many data recording devices and computer applications. Many people are also capable of importing and exporting various data formats into and from Excel. MATLAB also has commands for transferring data directly to and from formats such as csv and ASCII, as well as to the spreadsheet program Lotus 123. Details of these and many other commands can be found in the Help Window under File I/O

Importing and exporting data into and from Excel:

Importing data from Excel is done with the xlsread command. When the command is executed, the data from the spreadsheet is assigned as an array to a variable. The simplest form of the xlsread command is:

images

•   ‘filename’ (typed as a string) is the name of the Excel file. The directory of the Excel file must be either the current directory or listed in the search path.

•   If the Excel file has more than one sheet, the data will be imported from the first sheet.

When an Excel file has several sheets, the xlsread command can be used to import data from a specified sheet. The form of the command is then:

images

•   The name of the sheet is typed as a string.

Another option is to import only a portion of the data that is in the spreadsheet. This is done by typing an additional argument in the command:

images

•   The ‘range’ (typed as a string) is a rectangular region of the spreadsheet defined by the addresses (in Excel notation) of the cells at opposite corners of the region. For example, ‘C2:E5’ is a 4 × 3 region of rows 2, 3, 4, and 5 and columns C, D, and E.

Exporting data from MATLAB to an Excel spreadsheet is done by using the xlswrite command. The simplest form of the command is:

images

•   ‘filename’ (typed as a string) is the name of the Excel file to which the data is exported. The file must be in the current directory. If the file does not exist, a new Excel file with the specified name will be created.

•   variable_name is the name of the variable in MATLAB with the assigned data that is being exported.

•   The arguments ‘sheet_name’ and ‘range’ can be added to the xls-write command to export to a specified sheet and to a specified range of cells, respectively.

As an example, the data from the Excel spreadsheet shown in Figure 4-7 is imported into MATLAB by using the xlsread command.

images

Figure 4-7:  Excel spreadsheet with data.

The spreadsheet is saved in a file named TestData1 in a disk in drive A. After the Current Directory is changed to drive A, the data is imported into MATLAB by assigning it to the variable DATA:

>> DATA = xlsread('TestData1')
DATA =
 11.0000  2.0000  34.0000  14.0000  -6.0000        0   8.0000
 15.0000  6.0000 -20.0000   8.0000   0.5600  33.0000   5.0000
  0.9000 10.0000   3.0000  12.0000 -25.0000  -0.1000   4.0000
 55.0000  9.0000   1.0000  -0.5550  17.0000   6.0000 -30.0000

4.5.2   Using the Import Wizard

Using the Import Wizard is probably the easiest way to import data into MATLAB since the user does not have to know, or to specify, the format of the data. The Import Wizard is activated by selecting Import Data in the File menu of the Command Window. (It can also be started by typing the command uiimport.) The Import Wizard starts by displaying a file selection box that shows all the data files recognized by the Wizard. The user then selects the file that contains the data to be imported, and clicks Open. The Import Wizard opens the file and displays a portion of the data in a preview box so that the user can verify that the data is the correct choice. The Import Wizard tries to process the data, and if the wizard is successful, it displays the variables it has created with a portion of the data. The user clicks next and the wizard shows the Column Separator that was used. If the variable has the correct data, the user can proceed with the wizard (click next); otherwise the user can choose a different Column Separator. In the next window the wizard shows the name and size of the variable to be created in MATLAB. (When the data is all numerical, the variable in MATLAB has the same name as the file from which the data was imported.) When the wizard ends (click finish), the data is imported to MATLAB.

As an example, the Import Wizard is used to import numerical ASCII data saved in a .txt file. The data saved with the file name TestData2 is shown in Figure 4-8.

images

Figure 4-8:  Numerical ASCII data.

The display of the Import Wizard during the import process for the TestData2 file is shown in Figures 4-9 and 4-10. Figure 4-10 shows that the name of the variable in MATLAB is TestData2 and its size is 3 × 5.

images

Figure 4-9:  Import Wizard, first display.

images

Figure 4-10:  Import Wizard, second display.

In the Command Window of MATLAB, the imported data can be displayed by typing the name of the variable.

>> TestData2
TestData2 =
  5.1200   33.0000   22.0000   13.0000   4.0000
  4.0000   92.0000         0    1.0000   7.5000
 12.0000    5.0000    6.5300   15.0000   3.0000

4.6  EXAMPLES OF MATLAB APPLICATIONS

Sample Problem 4-1:   Height and surface area of a silo

A cylindrical silo with radius r has a spherical cap roof with radius R. The height of the cylindrical portion is H. Write a program in a script file that determines the height H for given values of r, R, and the volume V. In addition, the program calculates the surface area of the silo.

Use the program to calculate the height and surface area of a silo with r = 30 ft, R = 45 ft, and a volume of 200,000 ft3. Assign values for r, R, and V in the Command Window.

images

Solution

The total volume of the silo is obtained by adding the volume of the cylindrical part and the volume of the spherical cap. The volume of the cylinder is given by

Vcyl = πr2H

and the volume of the spherical cap is given by:

images

images

where h = RRcosθ = R(1 − cosθ), and θ is calculated from images. Using the equations above, the height, H, of the cylindrical part can be expressed by

images

The surface area of the silo is obtained by adding the surface areas of the cylindrical part and the spherical cap.

S = Scyl + Scap = 2πrH + 2πRh

A program in a script file that solves the problem is presented below:

images

The Command Window where the script file, named silo, was executed is:

images

Sample Problem 4-2:   Centroid of a composite area

Write a program in a script file that calculates the coordinates of the centroid of a composite area. (A composite area can easily be divided into sections whose centroids are known.) The user needs to divide the area into sections and know the coordinates of the centroid (two numbers) and the area of each section (one number). When the script file is executed, it asks the user to enter the three numbers as a row in a matrix. The user enters as many rows as there are sections. A section that represents a hole is taken to have a negative area. For output, the program displays the coordinates of the centroid of the composite area. Use the program to calculate the centroid of the area shown in the figure.

images

Solution

The area is divided into six sections as shown in the following figure. The total area is calculated by adding the three sections on the left and subtracting the three sections on the right. The location and coordinates of the centroid of each section are marked in the figure, as well as the area of each section.

The coordinates images and images of the centroid of the total area are given by images and images, where images, images, and A are the coordinates of the centroid and area of each section, respectively.

A script file with a program for calculating the coordinates of the centroid of a composite area is provided below.

images

images

The script file was saved with the name Centroid. The following shows the Command Window where the script file was executed.

images

Sample Problem 4-3:   Voltage divider

When several resistors are connected in an electrical circuit in series, the voltage across each of them is given by the voltage divider rule:

images

where νn and Rn are the voltage across resistor n and its resistance, respectively, Req = ΣRn is the equivalent resistance, and νs is the source voltage. The power dissipated in each resistor is given by:

images

The figure below shows a circuit with seven resistors connected in series.

images

Write a program in a script file that calculates the voltage across each resistor, and the power dissipated in each resistor, in a circuit that has resistors connected in series. When the script file is executed, it requests that the user first enter the source voltage and then to enter the resistances of the resistors in a vector. The program displays a table with the resistance listed in the first column, the voltage across the resistor in the 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.

Execute the file and enter the following data for νs and the R’s.

νs = 24V,     R1 = 20Ω,     R2 = 14Ω,     R3 = 12Ω,     R4 = 18Ω,     R5 = 8Ω,     R6 = 15Ω,     R7 = 10Ω.

Solution

A script file that solves the problem is shown below.

images

The Command Window where the script file was executed is:

images

4.7  PROBLEMS

Solve the following problems by first writing a program in a script file and then executing the program.

1.  The Heat Index HI, calculated from the air temperature and relative humidity, is the apparent temperature felt by the body. An equation used by the National Weather Service for calculating the HI is given by:

HI = −42.379 + 2.04901523T + 10.14333127R − 0.22475541R − 6.83783 × 10−3T2 − 5.481717 × 10−2R2 + 1.22874 × 10−3T2R + 8.5282 × 10−4TR2 − 1.99 × 10−6T2R2

where T is the temperature in degrees F and R is the relative humidity in integer percentage. Write a MATLAB program in a script file that calculates HI. For input the program asks the user to enter values for T and R. For output the program displays the message: “The Heat Index temperature is: XX,” where XX is the value of the heat index rounded to the nearest integer. Execute the program entering T = 90°F and R = 90%.

2.  The monthly saving P that has to be deposit in a saving account that pays an annual interest rate of r in order to save a total amount of F in N years can be calculated by the formula:

images

Calculate the monthly saving that has to be deposit in order to save $100,000 in 5, 6, 7, 8, 9, and 10 years if the annual interest rate is 4.35%. Display the results in a two-column table where the first column is the number of years and the second column is the monthly deposit.

3.  The growth of some bacteria populations can be described by

N = N0ekt

where N is the number of individuals at time t, N0 is the number at time t = 0, and k is a constant. Assuming the number of bacteria doubles every 40 minutes, determine the number of bacteria every two hours for 24 hours starting from an initial single bacterium.

4.  The volume V and the surface area S of a torus-shaped water tube are given by:

images

If r1 = 0.7r2, determine V and S for r2 = 12, 16, 20, 24, and 28 in. Display the results in a four-column table where the first column is r2, the second r1, the third V, and the fourth S.

images

5.  A beam with a length L is attached to the wall with a cable as shown. A load W = 500 lb is attached to the beam. The tension force, T, in the cable is given by:

images

For a beam with L = 120 in. and h = 50 in., calculate T for x = 10, 30, 50, 70, 90, and 110 in.

images

6.  Write a MATLAB program in a script file that calculate the average, standard deviation, and median of a list of grades as well as the number of grades on the list. The program asks the user (input command) to enter the grades as elements of a vector. The program then calculates the required quantities using MATLAB’s built-in functions length, mean, std, and median. The results are displayed in the Command Window in the following format:
“There are XX grades.” where XX is the numerical value.
“The average grade is XX.” where XX is the numerical value.
“The standard deviation is XX.” where XX is the numerical value.
“The median grade is XX.” where XX is the numerical value.
Execute the program and enter the following grades: 92, 74, 53, 61, 100, 42, 80, 66, 71, 78, 91, 85, 79, and 68.

7.  A rocket flying straight up measures the angle θ with the horizon at different heights h. Write a MATLAB program in a script file that calculates the radius of the earth R (assuming the earth is a perfect sphere) at each data point and then determines the average of all the values.

images

images

8.  Decay of radioactive materials can be modeled by the equation A = A0ekt, where A is the amount at time t, A0 is the amount at t = 0, and k is the decay constant (k ≤ 0). Iodine-132 is a radioisotope that is used in thyroid function tests. Its half-life time is 13.3 hours. Calculate the relative amount of Iodine-132 (A/A0) in a patient’s body 48 hours after receiving a dose. After determining the value of k, define a vector t = 0, 4, 8, …, 48 and calculate the corresponding values of A/A0.

9.  The monthly payment, P, of a N years mortgage of an amount L that with a yearly interest rate of r is given by:

images

where r is in % (e.g., 7.5% entered as 7.5). Write a MATLAB program in a script file that calculates P. When the program is executed it asks the user to enter the mortgage amount, the number of years, and the interest rate. The output is displayed in the following format: “ The monthly payment of a XX years XXXXXX.XX mortgage with interest rate of XX.XX percent is $XXXX.XX”, where XXX stands for the corresponding quantities. Use the program for determining the monthly payment of a $250,000 mortgage for 30 years and 4.5% yearly interest rate.

10.  The balance of a loan, B, after n monthly payments is given by

images

where A is the loan amount, P is the amount of a monthly payment, and r is the yearly interest rate entered in % (e.g., 7.5% entered as 7.5). Consider a 5-year, $20,000 car loan with 6.5% yearly interest that has a monthly payment of $391.32. Calculate the balance of the loan after every 6 months (i.e., at n = 6, 12, 18, 24, … , 54, 60). Each time, calculate the percent of the loan that is already paid. Display the results in a three-column table, where the first column displays the month and the second and third columns display the corresponding value of B and percentage of the loan that is already paid, respectively.

11.  Early explorers often estimated altitude by measuring the temperature of boiling water. Use the following two equations to make a table that modern-day hikers could use for the same purpose.

p = 29.921(1 − 6.8753 × 10−6h),      Tb = 49.161 lnp + 44.932

where p is atmospheric pressure in inches of mercury, Tb is boiling temperature in °F, and h is altitude in feet. The table should have two columns, the first altitude and the second boiling temperature. The altitude should range between −500 ft and 10,000 ft at increments of 500 ft.

12.  An isosceles triangle sign is designed to have a triangular printed area of 600 in.2 (shaded area with a base length of a and height of h in the figure). As shown in the figure, there is a 2 in. gap between the sides of the triangles. Write a MATLAB program that determine the dimensions a and h such that the overall area of the sign will be as small as possible. In the program define a vector a with values ranging from 10 to 120 with increments of 0.1. Use this vector for calculating the corresponding values of h and the overall area of the sign. Then use MATLAB’s built-in function min to find the dimensions of the smallest sign.

images

13.  A round billboard with radius R = 55 in. is designed to have a rectangular picture placed inside a rectangle with sides a and b. The margins between the rectangle and the picture are 10 in. at the top and bottom and 4 in. at each side. Write a MATLAB program that determines the dimensions a and b such that the overall area of the picture will be as large as possible. In the program define a vector a with values ranging from 5 to 100 with increments of 0.25. Use this vector for calculating the corresponding values of b and the overall area of the picture. Then use MATLAB’s built-in function max to find the dimensions of the largest rectangle.

images

14.  A student has a summer job as a lifeguard at the beach. After spotting a swimmer in trouble, he tries to deduce the path by which he can reach the swimmer in the shortest time. The path of shortest distance (path A) is obviously not the best since it maximizes the time spent swimming (he can run faster than he can swim). Path B minimizes the time spent swimming but is probably not the best, since it is the longest (reasonable) path. Clearly the optimal path is somewhere in between paths A and B.

images

Consider an intermediate path C and determine the time required to reach the swimmer in terms of the running speed νrun = 3 m/s the swimming speed νswim = 1 m/s; the distances L = 48 m, ds = 30 m, and dw = 42 m; and the lateral distance y at which the lifeguard enters the water. Create a vector y that ranges between path A and path B (y = 20, 21, 22, …, 48 m) and compute a time t for each y. Use MATLAB built-in function min to find the minimum time tmin and the entry point y for which it occurs. Determine the angles that correspond to the calculated value of y and investigate whether your result satisfies Snell’s law of refraction:

images

15.  An airplane is flying at a height of h = 900 ft while watching a target that is 70 ft tall (H = 70 ft), as shown in the figure. The best view of the target is when θ is maximum. Write a MATLAB program that determines the distance x at which θ is maximum. Define a vector x with elements ranging from 50 to 1500 with spacing of 0.5. Use this vector to calculate the corresponding values of θ. Then use MATLAB’s built-in function max to find the value of x that corresponds to the largest value of θ.

images

16.  The stress intensity factor K at a crack in a beam exposed to pure bending M is given by:

images

images

where images. a is the crack length, b is the width, t is the thickness, and C is a parameter that depends on the geometry of the specimen and crack. For the case of pure bending,

images

Write a program in a script file that calculates the stress intensity factor K. The program should read the values of M, b, t, and a from an ascii text file using the load command. The output should be in the form of a paragraph combining text and numbers,—i.e., something like: “The stress intensity factor for a beam that is 0.25 m wide and 0.01 m thick with an edge crack of 0.05 m and an applied moment of 20 N-m is XX Pa-sqrt(m).” where XX stands for the value of K. Use the program to calculate K when M = 20 N-m, b = 0.25 m, t = 0.01 m, and a = 0.25 m.

17.  The airplane shown is flying at a constant speed of ν = 50 m/s in a circular path of radius ρ = 2000 m and is being tracked by a radar station positioned a distance h = 500 m below the bottom of the plane path (point A). The airplane is at point A at t = 0, and the angle α as a function of time is given (in radians) by images. Write a MATLAB program that calculates θ and r as functions of time. The program should first determine the time at which α = 90°. Then construct a vector t having 15 elements over the interval 0 ≤ tt90°, and calculate θ and r at each time. The program should print the values of ρ, h, and ν, followed by a 15 × 3 table where the first column is t, the second is the angle θ in degrees, and the third is the corresponding value of r.

images

18.  The intrinsic electrical conductivity σ of a semiconductor can be approximated by:

images

where σ is measured in (Ω − m)−1, Eg is the band gap energy, k is Boltzmann’s constant (8.62 × 10−5 ev/K), and T is temperature in kelvins. For Germanium, C = 13.83 and Eg = 0.67 ev. Write a program in a script file that calculates the intrinsic electrical conductivity for Germanium for various temperatures. The values of the temperature should be read from an xls spreadsheet using the xlsread command. The output should be presented as a table where the first column is the temperature and the second column is the intrinsic electrical conductivity. Use the following values for temperature: 400, 435, 475, 500, 520, and 545 K.

19.  The pressure drop Δp in Pa for a fluid flowing in a pipe with a sudden increase in diameter is given by:

images

images

where ρ is the density of the fluid, ν, the velocity of the flow, and d and D are defined in the figure. Write a program in a script file that calculates the pressure drop Δp. When the script file is executed it request the user to input the density in kg/m3, the velocity in m/s, and values of the non-dimensional ratio d/D as a vector. The program displays the inputted values of ρ and ν followed by a table with the values of d/D in the first column and the corresponding values of Δp in the second column.
Execute the program assuming flow of gasoline (ρ = 737 kg/m3) at ν = 5 m/s and the following ratios of diameters d/D = 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.2.

20.  The net heat exchange by radiation from plate 1 with radius b to plate 2 with radius a that are separated by a distance c is given by:

images

images

Where T1 and T2 are the absolute temperatures of the plates, σ = 5.669 × 10−8 W/(m2-K4) is the Stefan-Boltzmann constant, and F1 – 2 is a shape factor which, for the arrangement in the figure, is given by:

images

Where X = a/c, Y = c/b, and Z = 1 + (1 + X2)Y2. Write a script file that calculates the heat exchange q. For input the program asks the user to enter values for T1, T2, a, b, and c. For output the program prints a summary of the geometry and temperatures and then print the value of q. Use the script to calculate the results for T1 = 400 K, T2 = 600 K, a = 1 m, b = 2 m, and c = 0.1, 1, and 10 m.

21.  Given the coordinates of three points (x1, y1), (x2, y2), and (x3, y3) it is possible to find the coordinates of the center of the circle (Cx, Cy) that passes through the three points by solving the following simultaneous equations:

images

Write a program in a script file that calculates the coordinates of the center and the radius of a circle that passes through three given points. When executed the program asks the user to enter the coordinates of the three points. The program then calculates the center and radius and displays the results in the following format: “The coordinates of the center are (xx.x, xx.x) and the radius is xx.x.”, where xx.x stands for the calculated quantities rounded to the nearest tenth. Execute the program entering the following three points: (10.5, 4), (2, 8.6), and (−4, −7).

22.  A truss is a structure made of members joined at their ends. For the truss shown in the figure, the forces in the nine members are determined by solving the following system of nine equations:

F2 + cos(48.81°)F1 = 0
 F6 + cos(48.81°)F5F2 = 0 ,
sin(48.81°)F5 + F3 = 0   −cos(48.81°)F1 + F4 = 0
−sin(48.81°)F1 + F3 = 1800,   −F4 − cos(48.81°)F5 = 1200 ,
F7 − sin(48.81°)F5 − sin(45°)F9 = 0 ,   sin(45°)F9 = 1500 ,
− cos(45°)F9F8 = 0

images

Write the equations in matrix form and use MATLAB to determine the forces in the members. A positive force means tensile force and a negative force means compressive force. Display the results in a table where the first column displays the member number and the second column displays the corresponding force.

23.  A truss is a structure made of members joined at their ends. For the truss shown in the figure, the forces in the 13 members are determined by solving the following system of 13 equations.

F2 + 0.7071F1 = 0 ,     −F2 + F6 = 0
F3 − 2000 = 0 ,
 F4 + 0.6585F5 − 0.7071F1 = 0
0.7071F1 + F3 + 0.7526F5 + 2000 = 0 ,   F7 + 0.6585F8F4 = 0
 0.7526F8 + F9 = 0 , F10 − 0.6585F5F6 = 0 ,   F9 + 0.7526F5 − 1000 = 0
0.7071F11F7 =0,     0.7071F11 + F12 + 3000 = 0,
F12 + 0.7526F8 − 2000 = 0 ,     F13 + 0.7071F11 = 0

images

Write the equations in matrix form and use MATLAB to determine the forces in the members. A positive force means tensile force and a negative force means compressive force. Display the results in a table where the first column displays the member number and the second column displays the corresponding force.

24.  The graph of the function f(x) = ax3 + bx2 + cx + d passes through the points (−2.6, −68), (0.5, 5.7), (1.5, 4.9), and (3.5, 88). Determine the constants a, b, c, and d. (Write a system of four equations with four unknowns, and use MATLAB to solve the equations.)

25.  The surface of many airfoils can be described with an equation of the form

images

images

where t is the maximum thickness as a fraction of the chord length c (e.g., tmax = ct). Given that c = 1 m and t = 0.2 m, the following values for y have been measured for a particular airfoil:

images

Determine the constants a0, a1, a2, a3, and a4. (Write a system of five equations and five unknowns, and use MATLAB to solve the equations.)

26.  During a golf match, a certain number of points are awarded for each eagle and a different number for each birdie. No points are awarded for par, and a certain number of points are deducted for each bogey and a different number deducted for each double bogey (or worse). The newspaper report of an important match neglected to mention what these point values were, but did provide the following table of the results:

images

From the information in the table write four equations in terms of four unknowns. Solve the equations for the unknown points awarded for eagles and birdies and points deducted for bogeys and double bogeys.

27.  The dissolution of copper sulfide in aqueous nitric acid is described by the following chemical equation:

images

where the coefficients a, b, c, d, e, f, and g are the numbers of the various molecule participating in the reaction and are unknown. The unknown coefficients are determined by balancing each atom on left and right and then balancing the ionic charge. The resulting equations are:

a = d,   a = e,   b = f,   3b = 4e + f + g,   c = 2g,   −b + c = 2d − 2e

There are seven unknowns and only six equations. A solution can still be obtained, however, by taking advantage of the fact that all the coefficients must be positive integers. Add a seventh equation by guessing a = 1 and solve the system of equations. The solution is valid if all the coefficients are positive integers. If this is not the case, take a = 2 and repeat the solution. Continue the process until all the coefficients in the solution are positive integers.

28.  The wind chill temperature, Twc, is the air temperature felt on exposed skin due to wind. In U.S. customary units it is calculated by:

Twc = 35.74 + 0.6215T − 35.75ν0.16 + 0.4275T v0.16

where T is the temperature in degrees F, and ν is the wind speed in mi/h. Write a MATLAB program in a script file that displays the following chart of wind chill temperature for given air temperature and wind speed in the Command Window:

images

29.  The stress intensity factor K at a crack is given by images where σ is the far-field stress, a is the crack length, and C is a parameter that depends on the geometry of the specimen and crack. For the case of the edge crack shown in the figure, C is given by:

images

images

Write a script file that will print out a table of values with the ratio a/b in the first column and the corresponding parameter C in the second column. let a/b range between 0 and 0.95 with increments of 0.05.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.221.144