This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
Victor E. Saouma new paragraph
Computing Literacy for Undergraduate Engineering Students
Draft
4{10
INTERNET
The telnet client must be told the hostname or the IP address of the host to which you want to connect. The machine on which the telnet client is started is the \local" machine. The host to which the client connects is known as the \remote" machine. Once connected, you must provide a valid username and password. These may be speci cally for you if you have an account on the remote machine. Otherwise, the username and password may be known to several users (or everyone); there may be no password required. In this case, the account is probably set up for a speci c purpose. A program is usually executed automatically (such as gopher or lynx), or the user is given a menu of choices when he or she logs in. Having successfully logged in, your local machine is functioning as a terminal of the remote. When logging in, make sure you are emulating the same type of terminal that the remote thinks you are emulating. Some common terminal types are: DEC vt100 family (vt100, vt102, vt220), ansi, and IBM 3270. The terminal type is set in the terminal emulation software (the telnet software) on the local machine. The remote may or may not prompt you to enter the terminal type after you login. Sometimes the remote gets a signal from the telnet client letting it know what type of terminal is in use. Some sites expect that only certain terminal types will be connecting to them and only function properly for that type.
4.3.1 Telnet Commands
open establishes a connection to the speci ed host. close closes an open connection and leaves you in telnet quit closes any open telnet sessions and exits the program set echo toggles screen echo on and o between full and half duplex CTRL- ] this key sequence puts you in telnet's command mode There are two methods for using telnet at the Unix prompt. First, you can just start the program, then issue the open command to get you connected to the desired host. Second, you can specify the desired host on the command line when you start telnet. This has the same eect as starting telnet then using the open command. It is a form of a short cut in that you are typing only one command. You are free to use telnet either way. You should also be aware that telnet uses a standard UNIX port to answer connections.
4.4 File Transfer Protocol (ftp) Since telnet does not have the ability to transfer les, the program ftp becomes very important. Ftp will allow you to transfer les between two computers systems. Additionally, one of the vast resources on the Internet is public domain software. In order for you to get to this software you will use a special instance of ftp known as anonymous ftp. This allows you to transfer les between two computers without having an account on the remote computer system. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
4.4 File Transfer Protocol (ftp)
4{11
4.4.1 De nitions
FTP: The Internet standard le transfer protocol. An ftp program is a user interface to this
protocol which allows the transfer to and from a remote network host. FTP Client: The local program which allows connection to an FTP server for the purpose of sending or receiving les. FTP Server: An Internet host which allows clients to connect and transfer les to or from the hosts. Anonymous FTP: Use of ftp to transfer les to or from a server which allows anyone to connect. The FTP server allows a user login ID of \anonymous" or \guest" and accepts any password input. The accepted courtesy on the Internet is for the use to provide his or her Internet email address. ASCII File: Text les are les that you can display on your screen and/or pull into a text editor. For example, AUTOEXEC.BAT and CONFIG.SYS are text les in DOS. Files you would usually transfer in ASCII mode include: \readme" les, source code, uuencoded, binhex, PostScript and HTML les. Files transferred in ASCII mode are \translated" so that they appear to be the same on the local machine as the remote. Text is stored dierently on dierent types of computers. PC text is represented dierently than Mac text. Neither PC nor Mac text is represented the same as Unix text. Those les are usually ASCII les: Text (.txt, tex, .asc); Source code (.c, .f, .for); e-mail messages; uuencoded les; PostScript (.ps); Hypertext (.htm, .html). Binary File: Binary les are not text les. This includes many le types such as: executables, images, sound, movies, spreadsheets, databases, word processing, and compressed les. Files transferred in binary mode are copied exactly, bit-for-bit. Those les are usually binary: Spreadsheets (.xls, ...); Databases (.dbf, .dbt); Word Processing (.doc, wp); Compressed les (.Z, .zip); Images (.gif, .tif, .ti, .jpg, .jpeg, bmp, pcx); Sounds (.au); Movies (.mpg, .mpeg, .mov). Download: An FTP client receiving a le from an FTP server using the \get" command is downloading the le. Upload: An FTP client sending a le to an FTP server using the \put" command is uploading the le.
4.4.2 Connecting to an FTP Server
To establish a connection with a remote host (FTP server) from the command line, simply type \ftp
Computing Literacy for Undergraduate Engineering Students
Draft
4{12
INTERNET
4.4.3 Basic Commands
The words with the \less-than" (<) and \greater-than" (>) signs are not literal, but indicate a real, situtationally-dependent word should be substituted. The information contained within the brackets (\[" and \]") are not required. cd
Computing Literacy for Undergraduate Engineering Students
Draft
4.5 Locating things on the Internet
4{13
4.4.4 A Sample FTP Session
4.5 Locating things on the Internet 4.5.1 Archie
browser interface to the Archie Internet Archives database. The best known application of the Archie system is to maintain the Internet Archives database. This database, already available from a number of service providers across the Internet, currently contains the names of over 2,100,000 les at over 1,000 anonymous FTP archive sites. Using this database, users can rapidly locate needed les without the need to log onto dozens or even hundreds of machines. Xarchie displays information returned from archie with an easy-to-use, point-and-click interface. It allows you to explore ftp sites by examining directories returned as query matches, and retrieves les located in this manner. Xarchie is designed (like most X applications) to be highly customizable. Almost all details of the interface, including display appearance and command interface, can be customized using X resources. When Xarchie is invoked, the main display is divided into horizontal areas. The top pane is a menu bar, and it contains the following buttons with the corresponding options: File presents the File Menu, from which you can select a variety of le-related operations. Settings displays the Settings Menu, for modifying the search type, the sort type, and the nice level. Query presents the Query Menu, which allows you to send your search request to archie. Abort active only during a query or le retrieval, this button allows you to abort either one. Help pops up the Help Panel. Underneath the buttons of the main window is the status bar. It provides information about the progress of a query, among other things. The middle pane of the Xarchie display functions as a host-location- le browser. The leftmost pane displays hostnames, the middle pane locations (or directories), and the rightmost pane les or directories returned by a query. You can adjust the relative size of the browser panes using the Grips on their borders. The bottom pane of the xarchie display provides a set of Text items where you can enter information and where information is displayed as query results are browsed. Typing return in some Text items invokes an action, as a shortcut for selecting it from a menu or button. For more information, consult
Xarchie is an X11
href="ftp://archie.ans.net/pub/archie/doc/whatis.archie href="http://web.nexor.co.uk/archie.html
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
4{14
INTERNET
or contact Bunyip Information Systems at (514) 398-3709 or (514) 398-811 or email [email protected]
4.5.2
y
4.5.3
y
Gopher
As strange as this may seem Gopher and a few companion utilities have done much to help eliminate the need for knowing IP addresses, hostnames, or even where things are located. In fact, a well constructed gopher service can eliminate many of the hassles associated with le transfers as well. Ftp sites and les just appear as another gopher menu item. A skillful Gopher keeper can mix key documents, crucial ftp sites, selected phone books, and useful telnet applications to create an invaluable set of menus for users to explore on their quest for Internet knowledge. However, it takes more than just a gopher service. Gophers take advantage of three key helpers to make nd information even easier. All three of these helpers create indexes that allow users to enter search critera to narrow an Internet quest. These three indexing tools are WAIS, Veronica, and Jughead. All three allow you to query Gopher, but each one indexes a dierent set of information. Let's take a look at the role of each of these indexing tools and then have you try a few searches on your own. However, before we do that let's discuss the program that got these guys going.
WAIS
WAIS stand for Wide Area Information Service. WAIS (pronounced ways) is a collection of distributed databases, which can be searched by keyword and cover a wide variety of subjects. WAIS is actually a set of programs or really a protocol that allows users to search and access dierent types of information from a single interface. WAIS existed before gopher, but has been adapted to use with gopher. WAIS databases can contain almost any kind of information from text to sound to images. Also the information does not have to reside on a single computer. WAIS is a set of client/server applications that are very useful in information retrieval. It has been added to the functionality of many of the newer systems, like Gopher, and World Wide Web. For more information, consult href="ftp://quake.think.com/wais/doc/overview.txt"
4.5.4
y
Veronica
Veronica stands for "very easy rodent-oriented net-wide index to computerized archives". Veronica is a utility that indexes the titles of all levels of menus for most gopher sites on the Internet. In essence Veronica is a search tool that you can use to build a new dynamic set of gopher menus focuses on the subject of your search. Think about the size of the Internet and the number of gophers around the world and then think about what Veronica is attempting to do. Now, do you think that Veronica searches are lighting fast? The important thing to remember about Veronica is that it is indexing gopher menu titles and no the actual information contained at the gopher sites. For more information, consult Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
4.6 RCP
4{15
href="ftp://veronica.scs.unr.edu/veronica-docs/veronica-faq" href="gopher://veronica.scs.unr.edu/"
4.6 RCP Rcp is a program to copy between UNIX machines. It stands for remote copy and it works much like the cp command. In order to use it, you must have the le .rhosts set up on the other machine. For instance, if you wanted to copy to or from spot, you must have a .rhosts on spot that has in it the machine you are logged into, say beethoven. See the section \Important Files" for information on exactly what should go in a .rhosts le. Once you have the .rhosts set up, you use rcp much like cp, except that to specify a le on the other machine, you use machine: before the le name. After machine:, you specify the path starting from your home directory. For instance, to copy a program from your home directory on spot to the current directory of the machine you're on, type rcp spot:program.c .
Or, if you have a subdirectory on spot named fortran, and want to copy a program in it to the current directory, giving it a new name, type rcp spot:fortran/program.f newprogram.f
You can copy the other direction, too. Again, just use machine: with the path to where you want the le. You can give a name if you want the destination le to have a name dierent from the one it has now. Say you want to copy newprogram.f back to spot after editing it. Type rcp newprogram.f spot:fortran/
Or replace program.f on spot by rcp newprogram.f spot:fortran/program.f
4.7 Kermit While kermit is not tied to the internet, we brie y mention it here as it is often used for le transfer between personal computers and UNIX systems. Most pc terminal programs support kermit as one of their le transfer options. If your program does not support it, then you may obtain pc-vt from the advisors in the computing center. The examples in this section assume that you are using pc-vt, other programs should be similar.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
4{16
INTERNET
4.7.1 Uploading
When you are transferring les from your pc to the suns, this is called uploading. Here are the steps necessary for uploading: 1. Log on to the Bechtel lab as you would normally using pc-vt. 2. Type kermit at the command prompt. 3. The prompt will change to C-Kermit> at this prompt type in receive filename. Where filename is what you want to call the le you are uploading to the system. 4. Type in ALT-K (hold down the alt and press the k key). This will activate kermit on the pc. 5. Your prompt will now be KERMIT-MS> and you should type send filename where filename is the le you wish to send. 6. Wait for the send screen to disappear and the KERMIT-MS> prompt to reappear. 7. Type exit at the KERMIT-MS> prompt. 8. You will now be at the C-kermit> prompt and you should type exit to end kermit. 9. You are now back to the system prompt and the le you uploaded will be in your current directory. SAMPLE SESSION: beethoven% kermit C-Kermit, 4D(061) 8 Sep 86, 4.2 BSD Type ? for help C-Kermit> receive sample.file ALT-k KERMIT-MS> send pc.file (wait till KERMIT-MS> prompt reappears) KERMIT-MS> exit C-Kermit> exit beethoven%
4.7.2 Downloading
When you are sending a le from the suns to a pc, it is called downloading. Here are the steps necessary for downloading a le to a pc. 1. Log on to the Bechtel lab as you would normally using pc-vt. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
4.8 y Mail and Listservs
4{17
2. Type kermit at the command prompt. 3. The prompt will change to C-Kermit> at this prompt type in send filename. Where filename is the le that you wish to download to the pc. 4. Type in ALT-K (hold down the alt and press the k key). This will activate kermit on the pc. 5. Your prompt will now be KERMIT-MS> and you should type receive filename where filename is the le you wish to receive. 6. Wait for the send screen to disappear and the KERMIT-MS> prompt to reappear. 7. Type exit at the KERMIT-MS> prompt. 8. You will now be at the C-kermit> prompt and you should type exit to end kermit. 9. You are now back to the system prompt and the le you downloaded will be on the pc. SAMPLE SESSION: beethoven% kermit C-Kermit, 4D(061) 8 Sep 86, 4.2 BSD Type ? for help C-Kermit> send unix.file ALT-k KERMIT-MS> receive pc.file (wait till KERMIT-MS> prompt reappears) KERMIT-MS> exit C-Kermit> exit beethoven%
4.8
y
Mail and Listservs
Email allows users to send and receive messages electronically. Messages are sent and received in seconds or minutes{much more quickly than possible by surface mail (\snail"). Messages will stay in the recipient's mail box until read. This decreases time spent \playing phone tag" or trying to contact someone in another time zone via telephone. Email can be useful for recording progress on projects (since messages can serve as a log of communications), for getting identical information to a potentially large group of people, and for automatically receiving information which may be of interest to you. Email can be used to send non-text (binary) data encoded as text data (uuencode, btoa, BinHex). Listservs allow a user to communicate with a group of users with particular interests. There are dierent lists for dierent topics. Subscribing to a list is analogous to adding yourself to Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
4{18
INTERNET
a mailing list. You receive all the messages sent to a list. The messages you send to a list are distributed to all other subscribers. The list may or may not be \moderated". If a list is moderated, someone is responsible for reviewing messages before they are mailed to the list. When you rst subscribe, you receive a message con rming your subscription to the list. You should save this message because it also tells you how to take yourself o the mailing list (unsubscribe). Subscribe/unsubscribe by sending a request to the mailing list's administrator (at the listserv address), not to the list. Addresses are usually composed of a username and hostname. Most Internet email addresses look like: username@hostname. For example, [email protected]. At CU, you may send an e-mail either one of two way: [email protected] If you know the loggin name and machine name of recipient. [email protected] You just need to know the rst and last name. The address goes in the \To:" eld of your email message. Most packages will accept multiple addresses in this eld. You can also send a copy of your message to yourself. The subject line goes in the \Subj:" eld of the message. The subject should give the recipient an idea of the contents of your message. Don't send any email messages that you would not want to become public. You could incorrectly address your message, your intended recipient could be forwarding his/her mail, or the recipient could forward your message. For the most part, UNIX uses two les. New messages that you receive are placed in your mail le in /usr/spool/mail/username and messages which you keep are kept in your mbox le in your login directory. When you enter UNIX mail, you can specify which le to use. If no messages are presently in the le, then you are told that there is no mail and are returned to the shell prompt. Note that the Bechtel Lab. supports a number of mail utilities: Mail Pine mh The following description is limited to \plain Mail".
4.8.1 Getting Started
To enter UNIX mail and check for new messages, type mail. UNIX mail will check your mail le for new messages. If there are no messages, it will give you a message like the following: bechtel% mail Mail version SMI 4.0 Wed Feb 7 23:10:16 PST 1990 "usr/spool/mail/username" : 0 messages No mail bechtel%
Victor E. Saouma
Type ? for help.
Computing Literacy for Undergraduate Engineering Students
Draft
4.8 y Mail and Listservs
4{19
Some mail systems may say only No mail for username
depending upon how your mail con guration le was initially set up (more on the con guration le later). If there are new messages, the their headers will be listed. bechtel% mail Mail version SMI 4.0 Wed Feb 7 23:10:16 PST 1990 "usr/spool/mail/username": 1 message 1 new >N 1 batman Mon Jan 7 10:15 9/168 "Hello"
Type ? for help.
The ampersand (&) is the UNIX mail prompt. As the message says, you can type ? and press
to the selected message, the N indicates the the message is new, the 1 is the assigned number of the message, batman is the person who sent the message, and "Hello" is the subject of the message. If you leave mail before reading a new message, the next time you enter UNIX mail, the N will be changed to a U (for unread). In order to act upon old (read) messages, you need to vary the mail command. By using the -f ag, you tell UNIX mail to use another le. The default -f le is your mbox le and it does not need to be speci ed. If you want to use another le, though, you will need to specify its name after the -f on the command line. For examples , to read messages from the mbox le, you do the following: bechtel% mail -f
To use the le todo, you would type bechtel% mail -f todo
4.8.2 Exiting From Mail
To exit from UNIX mail, type q (for quit) at the & prompt. This will preserve all the changes which you made while in UNIX mail. If you do not want to save the changes, you should type x (for exit) to reset the state of the le back to what is was before you entered UNIX mail1 .
4.8.3 Sending Messages
One method for sending UNIX mail is doing it directly from the shell prompt. To send mail, type mail, followed by the username of the recipient. You will be prompted for a subject and then you will be given a blank line. Type in the text of the message, ending it with
1 VMS users should note that this is the opposite from VMS usage, where ex (for exit) preserves changes and (for quit) resets the previous state.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
4{20
INTERNET
bechtel% mail batman Subject: Crime fighting This is the text of the message. ^D Cc: bechtel%
If at any point you decide not to send the message, you should type CTRL C. The aborted message text will be stored in a le called dead.letter in your login directory and you will receive the prompt back. You can also send messages from within UNIX mail. At the & prompt, type m (for mail), followed by the username. Use the same procedure as above to create the message. After entering your response to the Cc: prompt, though, you will again receive the & prompt. If you type CTRL D without entering any message, you will be given the following message when it is sent: Null message body; hope that's ok
If you need to send mail to a user on another machine, the username must include the machine name as well. username@machine_name
For example, to send a message to a user named wally at machine tramp, you would type: beethoven% mail wally@tramp
You will be noti ed it the machine name or username does not exist and your message will be returned.
4.8.4 Reading Messages
New messages are stored in your mail le. After calling up UNIX mail, you can screen the message headers before reading the messages. If you want to read the messages in order, just press
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
4.8 y Mail and Listservs
4{21
4.8.5 Replying to Messages
If after reading a message, you wish to reply to it, you can in two ways. By typing uppercase R, you can reply to the sender of the message. Typing lowercase r will reply to the sender, the people in the address line, and all of the people in the CC: list. Care should be exercised when replying so that you do not reply to anyone you did not intend to.
4.8.6 Message Headers
Message headers contain information about the messages. When you enter UNIX mail to read new message, the header information is displayed automatically. When you enter UNIX mail using your mbox le, you are given only the & prompt. Headers of new mail contain the extra character N (for new) or U (for unread). The other information in the same, regardless of how you enter UNIX mail. The following is a example of header information from a new mail le. & h 1 jeff Tue June 30 08:14 9/168 "test today" >U 2 trzyna Wed Jul 1 11:08 10/178 "date of mtg" N 3 plummer Wed Jul 1 11:38 32/104 "update" N 4 jeff Wed Jul 1 14:22 14/153 "first mtg"
The > points to the currently selected message. Any UNIX mail commands (without the message number included) will act upon this message. The status of the message is next (N=new, U=Unread, nothing=read), followed by the message number. Then comes the username of the sender, the date and time the message was received, and some system information. Finally, in quotation marks, is the subject of the message. If you are reading a message and would like to display the header information for that message, type f at the & prompt. This displays the header of the currently selected message.
4.8.7 Deleting Messages
To delete a message, type d at the & prompt. The currently selected message will be deleted. If you want to delete a particular message, type d followed by a message number. After deleting the message, you will no longer see the message header when you request a list of headers. If you delete a message by mistake, you may undelete it. If is is the message that you just deleted, then just type u at the & prompt. If it is another message, type u followed by the number of the message. For example, to undelete message number 2, type the following: & u 2 &
This procedure requires that you know the message number before you undelete it. If you have deleted a large number of messages, you have to undelete a few messages to nd the correct one if you don't remember the message number. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
4{22
INTERNET
You can undelete only those messages which you deleted during your current UNIX mail session. If you quit and re-enter UNIX mail, you cannot undelete messages that you deleted during a previous mail session. If you delete all the messages in a mail le, the le will be deleted from your directory when you quit. The following is an example of the message you will receive if you delete all the messages in the mbox le: & q "mbox" removed beethoven%
4.8.8 Saving Messages in Other Files
You may le messages that you receive into les other than the mbox le. To do so, you use the s command. Type s at the & prompt, followed by the name of the le. To access the messages in a particular le, you would enter UNIX mail with the mail -f command; followed by the name of the le. Using les is a good way to organize your messages. As an example, suppose that you wanted to keep a le which contained important messages that you needed to act on. You could call the le todo and le messages to it: & s todo "todo" [appended] 10/179
To use the todo le, you enter UNIX mail int the following way: beethoven% mail -f todo "todo": x messages &
Not all UNIX mail message can be categorize as messages, though. Sometimes you receive program source les or documents to edit. In those cases, you want to create les in your directory. For example, if you receive a C program, you might want to save it as a le. & s program.c "program.c" [New file] 10/179 &
In this example, you were noti ed that the UNIX mail created a new le. In the previous example, UNIX mail append the message to the todo le. When you use the s command, the message is appended to the speci ed le, if it exists. If it doesn't, a new le is created.
4.8.9 Forward, Vacation
To forward your mail from the Sun to another machine, simply include the other machine address in a .forward le. For example the following .forward le Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
4.9 NEWS
4{23
cours39%gcvaxa.epfl.ch@boulder,saouma
transfers all the incomming mail to another address, which happens to be in Switzerland (CH), while retaining a copy in the current machine. Should you be out of town, and would like to have: 1) a message automatically sent back to the originator of your incoming mail and 2) store and/or forward your mail, then you should use the vacation utility which will interactively prompt you for proper set-up.
4.9 NEWS
4.9.1 Introduction
News is world-wide system of communication. You can read about a variety of topics including various recreational activities, scienti c research, and computer systems. You can also post articles to be sent to local readers or across the globe asking information or providing it to others. There are a few informal rules about posting to news groups. Basically, you should just use common sense and courtesy in your postings. Remember, many thousands of people may be reading your posting and if they feel insulted, you may get hundreds of e-mail messages saying so! Some groups have more speci c guidelines about what should and should not be posted. For instance, source code in a binaries group is frowned upon, as are most discussions in source or binaries groups. In general, there are separate discussion groups to ask questions about source or binaries. You will get a much better response if you post to an appropriate group. For more detailed guidelines and help in general, read the group news.announce.newusers. You can read newsgroups from:
rn from an ascii terminal (or an xterm). xrn from an X terminal/station. Netscape Note that there is a news group dedicated to the discussion of the civil engineering bechtel lab called cu.civil. This group is used to give information relating to the lab. Things such as scheduled downtimes, lab problems, and program update notices are example of what you will nd here. Feel free to post to this group to get information to other users of the lab.
4.10 Sources 1. Cognitive Science Branch, National Library of Medicine, Bethesda, MD 2. E. Krol, University of Illinois, and E. Homan, Merit Network, Inc.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
INTERNET
Draft
4{24
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
Chapter 5
Graphics 5.1 Types of Images There are numerous format for digital image storage (see Table 5.1), however the most common formats are the following: gif is a very basic format which is limited to 256 colors, uses almost no compression scheme, and its usage on the web should be restricted to icons, bullets, charts, thumbnails, and other simple graphical applications. Interlaced gif is a special type of the gif format, for which the best analogy is to compare it to the opening of venetian blinds instead of the raising of a curtain. jpg format squeezes and compresses images, thus images take less room to store (though they may take a bit longer to interpret). This format can handle images with 24 bit resolution (i.e. 22 4 dierent colors), and because of the compression, images lose some data and sharpness. They should be used for photographic quality images, large and complex images. post-script is essentially a de facto graphics standard for printers. Most drafting and CAD programs can export into post-script. Note that post-script les, contrarily to most others, are ascii les.
5.2 Image Graphical Manipulation There are essentially two major tools available to Unix users convert which is a batch based program xv an interactive graphical program both can be freely downloaded from anonymous ftp sites. Window users have also access to numerous similar programs; probably the most widely used one being lview.
Draft
5{2
Graphics
5.2.1 convert
convert is a powerful program which converts an input le using one image format to an output
le with a diering image format and speci cation. c 1995 E. I. It was written by John Cristy, E.I. at du Pont De Nemours and Company it is du Pont de Nemours and Company convert recognizes the image types shown in Table 5.1. Commands supported by convert are shown in Table 5.2 Some examples: To convert a TIFF image to a Postscript A4 page with the image in the lower left-hand corner, use: convert -page 595x842+0+0 image.tiff document.ps
To convert a raw GRAY image to a portable graymap, use: convert -size 768x512 gray:raw image.pgm
To convert a Photo CD image to a TIFF image, use: convert -size 1536x1024 img0009.pcd image.tiff convert img0009.pcd[4] image.tiff
To create a visual image directory of all your JPEG images, use: convert 'vid:*.jpg' directory.miff
To identify the dimensions and the type of an image le, use: convert -verbose image null:
To reduce the size of an image by 40% convert -geometry 40% image.gif small.jpg
5.2.2 xv
For more information http://csep1.phy.ornl.gov/xv/xv.html
This is a reprint from
http://csep1.phy.ornl.gov/cornell proceedings/tutorials/Xv/overxv.html which was
sponsored by U.S. Department of Energy
c 1991, 1992, 1993, 1994, 1995 by the Computational Science Education Project, Department of Energy
xv is essentially similar to convert, though less powerful, yet interactive. This greatly facilitates its operation. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
5.2 Image Graphical Manipulation Tag AVS BMP CMYK EPS EPSF EPSI FAX FITS GIF GIF87 GRAY HISTOGRAM IRIS JPEG MAP MATTE MIFF MTV NULL PCD PCX PICT PNM PS PS2 RAD RGB RLE SUN TEXT TGA TIFF VICAR VID VIFF X XC XBM XPM XWD YUV YUV3
. Victor E. Saouma
5{3
Description AVS X image le. Microsoft Windows bitmap image le. Raw cyan, magenta, yellow, and black bytes. Adobe Encapsulated PostScript le. Adobe Encapsulated PostScript le. Adobe Encapsulated PostScript Interchange format. Group 3. Flexible Image Transport System. Compuserve Graphics image le. Compuserve Graphics image le (version 87a). Raw gray bytes. SGI RGB image le. Red, green, and blue colormap bytes followed by the image colormap indexes. Raw matte bytes. Magick image le format. NULL image. Photo CD. ZSoft IBM PC Paintbrush le. Apple Macintosh QuickDraw/PICT le. Portable bitmap. Adobe PostScript le. Adobe Level II PostScript le. Radiance image format. Raw red, green, and blue bytes. Utah Run length encoded image le; read only. SUN Raster le. raw text le; read only. Truevision Targa image le. Tagged Image File Format. read only. Visual Image Directory. Khoros Visualization image le. select image from X server screen. constant image of X server color. Specify the desired color as the lename. X11 bitmap le. X11 pixmap le. X Window System window dump image le. CCIR 601 4:1:1 le. CCIR-601 4:1:1 les.
Table 5.1: Types of Images Supported by convert
Computing Literacy for Undergraduate Engineering Students
Draft
5{4
OPTIONS
Graphics
DESCRIPTIONS
Image Enhancement blurr an image by a user speci ed factor surrounds the image with a border enhance or reduce the image contrast apply Floyd/Steinberg error diusion to the image detect edges with an image apply a digital lter to enhance a noisy image perform histogram equalization to the image level of gamma correction the type of interlacing scheme This option speci es the font to be used for displaying normal text. vary the brightness, saturation, and hue of an image reduce the noise in an image with a noise peak elimination lter sharpen an image Image Geometry
ip create a "mirror image" by re ecting the image scanlines in the vertical direction
op create a "mirror image" by re ecting the image scanlines in the horizontal direction. density vertical and horizontal density shear shear the image along the X or Y axis by a positive or negative shear angle crop preferred size and location of image geometry preferred size or location of the image roll roll an image vertically or horizontally rotate apply Paeth image rotation to the image sample scale image with pixel sampling scene image scene number size width and height of the image Image Colors colors color reduction option colorspace type of colorspace (rgb, cmy, etc...) map choose a particular set of colors from this image monochrome transform the image to black and white negate apply color inversion to image normalize transform image to span the full range of color values. This is a contrast enhancement technique undercolor control undercolor removal and black generation on CMYK images Misc. comment annotate an image with a comment page preferred size and location of the Postscript page quality JPEG quality setting verbose print detailed information about the image blur border contrast dither edge enhance equalize gamma interlace font modulate noise sharpen
Table 5.2: convert commands
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
5{5
Draft
5.2 Image Graphical Manipulation
Figure 5.1: xv initial window
5.2.2.1 Introduction Xv is an interactive image manipulation program for the X Window System. It can operate on images in the GIF, JPEG, TIFF, PBM, PGM, PP, X11 bitmap, Sun Raster le, RLE, RGB,BMP, PCX, and PM formats on all known types of X displays. It can generate PostScript les, and if you have ghostscript version 2.5 or above installed on your machine, it can also display postscript les. The function of this overview is to get you familiarized with some of the basic options that Xv provides so that you feel con dent manipulating the package. We will start with the "getting to know you" exercises, and then if you wish, there is much more detailed information available later. Xv is a fascinating tool; you can experiment with the various commands on your own if the beginning exercise piques your interest.
5.2.2.2 Starting xv If Xv is installed and in your path, it can be invoked from an X Window environment by entering xv This will bring up Fig. 5.2 To open up the control box hit the right mouse button. This will display Fig. ??. Loading a le will take you to Fig. 5.3.
5.2.2.3 Grabbing
Click the left mouse button on the Grab box in the control window. You will hear a beep which tells you Xv is ready to roll. Now move your mouse to the window containing the image you wish to grab. If you hit the left mouse button (which we all have a tendency to do being an index- nger oriented society), the whole window will be saved. Since this would include the overview prose and the Mosaic outline and options, this is not desirable in this instance. Instead, go to one of the corners of the image you wish to save, and use the middle mouse button. Hold this down to drag a rectangle over the desired image. When you have the image Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Graphics
Draft
5{6
Figure 5.2: xv Control Panel
Figure 5.3: xv Loading a le Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
5{7
Draft
5.2 Image Graphical Manipulation
Figure 5.4: xv Saving a le outlined to your satisfaction, release the mouse button. The original Xv window will show you what you have \grabbed". This may take several tries until you become accustomed to the maneuvers.
5.2.2.4 Saving The Save button available in the control window. This will bring up Fig. 5.4
Make sure you are in the directory of your choosing. In this image, we are in the Xv directory. You can change directories by clicking on the box over the le listing. Then place the mouse in the Save le: box and type in the name of your choosing. The ending of the name should re ect the le format of your choice. Once you have chosen the format and clicked on the respective button, click on Ok and the window will close. In the control window you should see a message as to whether or not the image was successfully saved.
5.2.2.5 Changing the size The original Xv window should still have the image you grabbed earlier. If you want to change the size of this image, you have many options. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Graphics
Draft
5{8
Figure 5.5: xv Color Editing
Dbl Size will double the size of the image Half Size will half the size of the image SetSize enables you to choose the speci c size desired Maxpect will make the image as large as possible and still retain the integrity of the original image
Max Size will make the image cover the entire screen Normal will change the image back to the original size 5.2.2.6 Editing the colors Now click on the ColEdit button in the Xv control window. This should bring up the intim-
idating \xv color editor" window, Fig. 5.5 In the rst third, you have the option of using the Random button. This will change the colors of the image drastically. if you wish to return to the original image, click on Reset. Remember that Reset button is there if you get too
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
5.3 Screen Dump
5{9
panicked. In the second third, there is a circle that had the word White underlined at the top left. If you click on the button in the center and move it around the circle (between Yellow, Green, Cyan, Blue, Magenta, and Red), you can change the background colors. When you nd an image you like, then exit the color editor by clicking on the Close button residing in the rst third of the window. The image you ended with will be the one showing in the Xv window. You can save this new image under a dierent name than the rst.
5.2.2.7 Viewing using the Visual Schnauer Click on the Visual Schnauzer in the Xv control window. This will bring up another This window enables you to: 1. Pull up various les by double clicking on any of the les shown. 2. View all images saved into a particular directory. If some of the images are not shown, hit the Update button to update the window.
5.3 Screen Dump It is often desirable to generate a digital image out of the entire screen or of a particular window. This can be easily accomplished using xwd. To generate the desired le: 1. xwd -out fn to dump a window in le fn. After you hit the return key, move the mouse and click on the window. A double beep will con rm the le saving. 2. convert fn fn.gif to convert the le from xwd to gif format (alternatively you may try xwdtopnm infile >outfile to convert the le to pnm format for xv viewing 3. xv to view it, possibly modify it, and save it.
5.4 Scanning Pictures Pictures may be scanned in the Bechtel Lab (CE 1-09) or in the CAD lab oce (CE 1-03B).
5.4.1 Scanning Pictures in the CAD lab
Lab advisors are available in the CAD lab from 6-11 p.m. Monday through Friday to allow students and faculty access to the scanner. Once on the PC in the CAD lab oce: Open MicroSoft Windows Click twice on the Deskscan icon Place picture in the upper left corner of the scanner Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
5{10
Graphics
Preview picture but clicking once on the Preview button in the bottom right hand corner of the window Under Custom and then under Image Size set the image size you desire Under File specify a name for the image you wish to scan and save the image as a TIFF 5.0 le (write down this name because you will need it in the next step) Once you have scanned the image you need to transfer it to you Bechtel Lab account to insert it into an html document. To transfer the image to your Bechtel Lab account simply: Click twice on the DOS shell icon from within Windows Type cd deskscan Type move *.tif .. Type dmenu Select the Applications menu and then select CUTCP Connectivity Select the last item on the list, ftp When the box pops up with a prompt, type bechtel At the Login: prompt enter you login name and then at the Password: prompt enter your password Now you are ready to transfer the image le... type bin at the ftp> prompt Type put lename.tif, where lename is the name of your image le as saved in step number 6. above. As soon as you are back at the ftp> prompt type quit Now your picture is located on your account in the Bechtel lab and ready to be put into Netscape.
5.4.2 Scanning Pictures in the Bechtel Lab
It is advised that you use the scanner in the CAD lab, but if it is unavailable the Bechtel lab has a scanner also. To use this scanner simply: Login to the machine named faure Get into OpenWindows Type Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
5.5 Animation
5{11
/usr/local/scan/bin/openscan
Place your picture in the upper right hand corner of the scanner Set the Scan Width and Scan Length Click once on the scan button and wait for the scanner to nish scanning Click once on the upper left corner of the picture window to push the window pushpin in Type in a lename in the upper right corner of the screen with a *.gif extension
NOTE: If faure is not available you may login to another machine in the lab and then type the following in your shelltool: 1. xhost +faure 2. rlogin faure 3. setenv DISPLAY your_machine_name:0.0 across the top of your screen)
(your machine name is located
5.5 Animation Given that a series of sequential images have been collected, one may be interested in generating an \animation" le or a \movie" out of them. One of the major standards for such a le is MPEG (or les with an .mpg extension). In the Bechtel Lab, the mpeg encode utility would enable you to generate an .mpg le out of .yuv les (which in turn can be generated by the convert program from .jpg or other le format). For additional information, consult the man pages.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Graphics
Draft
5{12
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
Chapter 6
World Wide Web 6.1 Introduction The World Wide Web (WWW) is a hyperlink environment, developed by CERN (Switzerland), to connect text (html les), graphics (post-script les), images (jpg, gif les), movies (peg les), and sound (snd les) les across the internet.
6.2 Access to the WWW With a browser it is possible to view documents (including pictures, and sounds), download les through ftp, send e-mail, submit forms, and last but not least seek and retrieve information. The three major browsers are: Netscape By far currently the most popular, powerful and versatile browser. Mosaic Listed only for \historical" reasons. lynx for quick, non-graphical, browsing through a plain text terminal.
6.3 Netscape Primer Netscape is (currently) the most widely used Web Browser, Fig. 6.1. Hence, we should familiarize ourselves with its basic operations.
File Enables you to open remote or local les, as well as save les. View Can view the raw source code (html le of the current page), great to learn from others
development. Go To view a recently accessed documents. Presents the titles of documents viewed during current session which may be selected and viewed again. These document links are NOT
Draft
6{2
World Wide Web
Figure 6.1: Netscape Control Panel preset by Netscape, rather the links presented are based on your Internet exploration path. Bookmarks Record a document for instant access by adding it to the Bookmarks list. Options Set default options. Net Directory Search for topics on the Internet. Back Revisit the previous Web page. Forward Move to the next Web page in a series. Home Load up the default home page. Reload If an image fails to appear in the document, "Reload" can be used to transfer the document information again. This will sometimes bring the image on the screen. If the image does not appear after the second or third reload, the document is designed incorrectly and the image will not appear until the document designer xes the problem. Open Jump directly to a speci ed URL Print is a useful feature which allows the user to print text and/or images on a printer. Be careful when using a Laser printer. The text will print the same size as it appears on in Netscape window and use lots of paper. Change the font size in the "Fonts and Colors" menu if necessary. Find will search the current document for a user speci ed string of characters. Stop perhaps one of the easiest and most useful tool in Netscape. Pressing "Stop" will cease the connection attempt or transfer of information which is currently in process. Use "Stop" when: 1. After pressing a link, a new document or picture does not appear after a long wait. Long waits are often due to increased user trac. Some documents take longer to access than others. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
6.3 Netscape Primer
6{3
2. You decide a sound, image or animation le being downloaded is taking too long to download because of its large size. Some sound and animations can be quite large and take time to download. Finally, you could use the right or left mouse buttons as \shortcuts" to certain operations. A very useful one is the capability of separately downloading an image le (if the mouse cursor is placed on top of it).
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
World Wide Web
Draft
6{4
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
Chapter 7
World Wide Web The Web is a worldwide network of data. This computer network is itslef composed of clients and servers. The servers are computers which hold most the les, data and resources (Bechtel is a web server, and all ohter workstations are mere clients). Individual computers themselves are the clients which access the server. A Web browser is a client program. The Web is nothing else than a tangle of client-server interactions.
7.1 Protocols For this global communication to occur, there has to be a standard. In that standard, it does not matter what is being transmitted (text, graphics, images, sounds, movies) all are treated the same way. This is done through a very simple protocol known as HTTP for Hypertext Transfer Protocol. Just as to each telephone is assigned a phone number, to each internet user a unique email address, each internet resource ( le or docment) has its own URL or Universal Resource Locator. Each URL consists of the following elements: 1. The scheme, protocol or type of internet service the resource is using. Examples of services include: http ftp mailto le gopher news telnet rlogin tn3270 wais 2. The name of the host computer on which the resource is stored. 3. The directory where the resource is stored. 4. The name of the resource itself. Examples:
Draft
7{2
World Wide Web http://bechtel.colorado.edu/~smith/share/share.html The Hypertext
Transfer Protocol quickly and eciently cll s up any web page which may contain text, graphics, sounds or other supported items. Most (but not all) Web pages are written in HTML or Hypertext Markup Language.
to retrieve a le by logging you as an anonymous visitor. mailto://[email protected] Letss you send an e-mail to a speci ed user. news:cu.civil Allows you to access a news server. telnet://caruso.colorado.edu Allows you to telnet into a remote computer.
ftp://ftp.colorado.edu
7.2 An HTML Tutorial Since numerous tutorial on HTML programming have already been developed and are accesible through the Web, I will not even attempt to rewrite one. However, you are expected to 1. Go in details through the following section which contains a commented sample html le (which you may retrieve through anonymous ftp at /pub/Structures/Saouma/sample.html in the Bechtel Lab. 2. Go through the following on line tutorials: http://union.ncsa.uiuc.edu/HyperNews/get/www/html.html http://union.ncsa.uiuc.edu/HyperNews/get/www/html/learning.html http://union.ncsa.uiuc.edu/HyperNews/get/www/html/guides.html
7.3 Location of html les You can place your html les any where you want in your directory. For instance: http://civil.colorado.edu/~smith/project/homepage.html is a valid URL address. Yet a better place to store your homepage will be in the following directory ~/public html
which has a special meaning, and thus your URL address will be http://civil.colorado.edu/~smith/homepage.html
Finally, should you link le index.html to homepage.html (or simply have le index.html as your homepage le), then your URL will be even more compact (and easier to remember) http://civil.colorado.edu/~smith
Note that you can have your homepages on any computer on campus, for instance
http://ucsu.colorado.edu/~smith
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
7.4 HTML Functionality
7{3
7.4 HTML Functionality In general HTML can mark: Hyperlinks: Icons, text, or pictures that when clicked, will transfer you to a dierent part of the Internet, and display a dierent Web page. Formating: Font styles, text types. Structure: Section headings, paragraph and line separator, tables. Lists: bulleted, numbered, unnumbered. Graphics: Photographs, charts, logos, icons, thumnails. Forms: Database-type forms complete with text elds, pick lists, menus, check boxes, and radio buttons. Note that HTML is continuoulsy growing and evolving, the most recent version (1996) is HTML3. It should be noted that this version is not yet universal, however Netscape can already handle most of its features.
7.5 Anatomy of an HTML le The best way to learn html programming is by examining a sample le, decipher it, test it, modify it. This will be enough to get you started. In addition you will nd plenty of information on html programming directly on the web, hence there is absolutely no need to provide ample written explanations in this handout.
Tag specifying to the browser that what follows is an HTML le (optional)
> < < < < <
browser.
> >
> >
> close the body initial tag.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
7{4
World Wide Web
>
width=50
Bring in an image and
begin a header of order 1
John Smith Home Page Text to be displayed /h1 end header /center hr size=3 width=75% Draw a horizontal line (hr) width 3, and only over 75% of the width br break (i.e. new line) font size=4 Anything which follows will have a font size of 4 I am an text strong begin boldface undergraduate /strong end boldface student in the a href=http://civil.colorado.edu/index.html establish a link to .../index.html Civil Engineering Link is established whenever user clicks on this text. /a close the anchor Dept. p new paragraph font size=2 From here on, use font size 2 I am currently taking blink start blinking cven-4837 this text will be blinking /blink end blinking which covers br break img src=/bechtel/users5/ceae/Pictures/ball.green.gif Insert a bullet Intro to Unix Text br img src=/bechtel/users5/ceae/Pictures/red.green.gif Internet, HTML Programing
< > < > < < > < > <
>
>
<
>
<
>
< > <> < < <
>
>
>
< > <
< ><
>
>
MATLAB
Start a table with (optional) border size of 5
end table Begin a new row end row Text header which will span 4 columns Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
7.5 Anatomy of an HTML le
7{5
Undergraduate Text tr Begin new row td Begin new cell Freshman cell entry td Sophomore td Junior td Senior etc.. tr td align=right 3.0 td align=center 3.2
< > < >
< > < ><
< > >
ment
<
< >
>
3.1 3.7 note optional align-
E-Mail:
<
><
>
More Help /h2 /center For more information on html programming, please consult ul begin unnumbered list li List entry a href=http://union.ncsa.uiuc.edu/HyperNews/get/www/html.html HyperText Markup Language (HTML) a text li a href=http://union.ncsa.uiuc.edu/HyperNews/get/www/html/learning.html Learning HTML a li a href=http://union.ncsa.uiuc.edu/HyperNews/get/www/html/guides.html Guides to Writing HTML Documents a /ul end unnumbered list /BODY Closing body tag. /HTML Closes the html tag.
< > < > <
< ><
< >< < < <
>
>
<>
>
<>
<>
>
> >
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
World Wide Web
Draft
7{6
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
Chapter 8
XMGR 8.1 Introduction xmgr is an extremely powerful graphing tool developed for the Sun workstations. xmgr is capable of producing almost any type of 2-D graph and is capable of performing many advanced mathematical functions, such as; digital ltering, spline curve tting, linear regression, fourier series, and more. It is a very exible program in that it allows the user to de ne how the data is to be read. Because it is exible and very advanced, it is not the easiest program to use. However, it's use is recommended because it can eliminate a considerable amount of programming eort, Fig. ??. A few of xmgr's features are:
Polynomial regression, splines, running averages, DFT/FFT, cross/auto-correlation. Plots up to 11 graphs with 15 datasets per graph. User-de ned scaling, tick marks, labels, symbols, line styles, colors. Batch mode for unattended plotting. Read and write parameters used during a session. Support through device independent graphic drivers for HP75xx plotters, PostScript, Sun raster les, and the HP LaserJet II. In general, xmgr requires two input les: 1. A numerical data le containing the data. 2. a parameter le containing information regarding the display of the plot (such as titles, tic mark spacing, etc..). If the plot is being generated for the rst time, xmgr will create the parameter le for you.
Draft
8{2
XMGR
8.2 Starting up XVGR
To start up xmgr, from the shelltool type > xmgr &
8.3 Exiting XVGR
To exit xmgr: 1. Click on File (with left button). This will pop-up a window. 2. With the left mouse button click on Exit.
8.4 Data les
When there is more than one data set in a le each data set must be terminated by & Comment lines may be included anywhere as long as they are preceded with a # Files containing numeric data can have three basic formats: Two column format: This can be used for single or multi-data sets. The rst column contains X axis data and the second contains y axis data. For example:
# Example of a single set of two column format 282.553000 -0.167460 282.595000 -0.126310 282.637000 -0.130120 282.678000 -0.119800 282.720000 -0.037540 282.762000 -0.002380 # Not sure about this last point. experiment went wrong 282.803000 -0.022020 &
Another example may have two separate data sets with dierent X's: # Experimental Data 2. 22. 3.5 25. 4.2 36. 5.8 40 6.2 42. & # Numerical Prediction
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
8.4 Data les 1. 2. 3. 4. 5. 6. 7. 8. &
8{3
15. 21. 23. 30. 38. 41. 44. 45.
Multi column data: Quite often several data sets have the same corresponding X axis data. The multi column format is well suited for this data. The rst column contains X values and the remaining columns (up to 15) contain corresponding Y values.
# data 1.0 2.0 3.0 4.0 5.0 6.0 7.0 &
set 1 22.5 20.5 18.4 17.1 15.6 13.4 11.0
20.2 18.3 16.7 14.9 13.0 11.1 8.7
-25.5 -23.3 -20.9 -18.9 -17.1 -15.0 -13.2
IHL format: A 3 column data le with the rst two lines giving one line of alpha and the second an integer value with the number of points to follow. What ever that means!
Sample data les can be found in the directory: /usr/local/lib/xmgr.
8.4.1 Parameter File
The parameter le is best de ned interactively through xmgr and then saved. Do not attempt to edit it. Note that the same parameter le can be used for any data set. If you want your data set to be displayed using a prede ned parameter le, you must rst read in the parameter le before you load in your data. Sample parameter les can be found in /usr/local/lib/xmgr.
8.4.2 Reading an Input File
Once xmgr has been \ red-up", 1. Click on File (with right button). This will pop-up a window. 2. With the left mouse button click on Read Sets. This will pop up a menu with a list of all the les that have been found in the current directory. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
8{4
XMGR
3. With the left mouse button, select the le you wish to be loaded. 4. Underneath the list of les appears File Type. If your data is not in an XY format select File Type with the right mouse button, this will pop up a list of format options, choose the appropriate one with the left mouse button. 5. Once you are done select the Accept button at the bottom of the window, with the left mouse button.
8.5 Generating a Plot
Once you have loaded your data into xmgr, if you have not used a parameter le, you will notice that it automatically plots your data in a prede ned window. In all likelyhood you will need to rede ne the size of this window, as well as create a heading for your plot, and labels for the axises.
8.5.1 Changing the Size if the Plot Window
To rede ne the values of Xmax, Xmin, Ymax, and Ymin: 1. Click on View with the right mouse button. This will pop up a menu. 2. Click on Define world... with the left mouse button. This will pop-up another menu. 3. This last menu will allow you to modify the max and min values of X and Y axises, and also let you modify the placing of tick marks. Another way to do this is to use the Autoscale function located uder View, or click on the AS button at the top of the xmgr window. Both of these options will automatically resize the window to t your data.
8.5.2 De ning Labels for your Plot
To de ne X and Y-axis labels for your plot: 1. Click on View with the right mouse button. This will pop up a menu. 2. Click on Ticks/tick labels... with the left mouse button. This will pop-up another menu. 3. Click on Edit: with the right mouse button, this will allow you to choose which axis you will be modifying. 4. The next line, called Axis label is where you type in your label. 5. when you are done modifying this portion of your plot click on the Accept button with the left mouse button. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
8.5 Generating a Plot
8{5
8.5.3 De ning a Title for your Plot
De ning a heading for your plot is done similarly to de ning labels: 1. Click on View with the right mouse button. This will pop up a menu. 2. Click on Title/subtitle... with the left mouse button. This will pop-up another menu. 3. This last menu will prompt you to type in a title. The subtitle is optional. 4. when you are done modifying this portion of your plot click on the Accept button with the left mouse button.
8.5.4 Plotting Multiple Datasets
To plot another set of data on the axis displayed in the plot window, simply repeat the steps for loading up a le. 1. Click on File (with right button). This will pop-up a window. 2. With the left mouse button click on Read Sets. This will pop up a menu with a list of all the les that have been found in the current directory. 3. With the left mouse button, select the le you wish to be loaded. 4. Underneath the list of les appears File Type. If your data is not in an XY format select File Type with the right mouse button, this will pop up a list of format options, choose the appropriate one with the left mouse button. 5. Once you are done select the Accept button at the bottom of the window, with the left mouse button.
8.5.5 Changing the Plot Symbols
You may also change how your data sets are displayed. For instance if you have multiple datasets on one plot you may wish to have one dataset ploted using a dotted line, and another plotted using a dashed line. Another example would be if you have done some sort of t to your data you may wish to see the actual data points plotted on the tted curve. All this is done from the Symbols option of the View menu. After you have clicked on Symbols you will get a window. If you have multiple data sets, you will need to de ne which one you wish to modify. This can be done by clicking on Select set with the right mouse button, then select the number of the dataset you wish to modify. Xvgr numbers your sets starting with zero for the rst set loaded, one for the second set loaded, etc. If you wish to plot out your data as points Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
8{6
XMGR
1. 2. 3. 4.
Click on Symbols with the left mouse button. Choose which symbol you wish to represent your data points, with the left mouse button. Click on Style with the right mouse button. Choose None with the left mouse button. This will shut o the line-drawing operation, so your data will be plotted as the symbols you have speci ed. 5. Lastly, click on Accept with the left mouse button, and this will redisplay your data in the new format. If you wish to change the style of the line that represents your data: 1. Chose the data set you wish to modify, as explained above. 2. Click on Style with the right mouse button. 3. Choose one of the options listed, with the left mouse button. 4. Click on Accept with the left mouse button, and this will redisplay your data in the new format. Once you have nished modifying your display, click on Done with the left mouse button.
8.5.6 De ning a Legend for your Plot
If you have multiple data sets plotted on one graph you may wish to de ne a legend for the graph. This can be done as follows: 1. You need to follow the steps in the preceding section for rede ning the plot symbols. 2. Next click on View with the right mouse button, then click on Legends with the left mouse button. 3. On the top line of the window is Legend, click the ON button with the left mouse button. 4. Click Legend location type with the right mouse button, and choose World coordinates. 5. To place the legend on your plot, click Place with the left mouse button, then place the pointer on your plot where you wish the legend to appear and click the left mouse button again. 6. Click on Load comments with the left mouse button to set the legend comments. The default is to name each dataset with the lename that the set was loaded from, if you wish to change this, this can be done from the Symbols menu, by editing the line Legend: on Symbols menu. Sometimes the legend will not end up exactly where you wanted it to be. You can move the legend around by editing the Legend X: and Legend Y: lines on the Legend menu. The world coordinates of the current pointer position are listed at the top of the xmgr window, this will help you with ne tuning the legend position. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
8.6 Plotting Multiple Frames in one Window
8{7
8.6 Plotting Multiple Frames in one Window To view multiple plots in a non-overlapping format you would: 1. Click on View with the right mouse button. 2. Click on Graphs with the right mouse button. 3. Click on Arrange Graphs... with the left mouse button. 4. Select the number of rows, and columns you wish to be displayed. The layout will start from the lower left and go up each column, for example given 3 columns and 2 rows the graphs would be laid out as follows: 1 3 5 0 2 4
Note: the numbering starts at 0. 5. Select the packing method. Use this item when there are several graphs with the same X or Y axis scaling so graphs on the outside of the packing arrangement provide the tick and axis labeling for all graphs in that row, or column or both. 6. The next selections will determine the individual graph size and how much space to leave between each graph. These coordinates are in viewport coordinates. They can be thought of as percentages of the graph window. For example if you were to have one row of two graphs, you would want to de ne the width of each graph as slighlty less than 50% of the graph window, or Graph width as .45, and something similar for graph height. 7. You can adjust the Start at X and Start at Y to center your graphs in the window. This will position the rst graph. 8. When you have nished making your selections click the Accept button with the left mouse button. 9. When you are satis ed with your plot click on Done with the left mouse button. Because of the interactive nature of xmgr, arranging your plots in the graph window may be an iterative process. You may continuously adjust the starting point of the graphs, or the height and width of the plots, etc., until you get the desired results.
8.7 Getting a Hardcopy of your Plot To print a plot that is currently showing in the plot window: 1. Click on File with the right mouse button. 2. Choose Print with the left mouse button. This will automatically send a copy of your plot to the printer. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
8{8
XMGR
8.8 Saving Your Plot to a File If you wish to save your plot in a le: 1. Click, with the left mouse button on Printer setup. This will pop up a window. 2. Click with the right mouse button on Print to. This will display two options Printer or File. 3. Click on File with the left mouse button, this will then prompt you for a le name for your plot. 4. Once you have entered the le name, click on the Print button at the bottom of this window with the left mouse button. This will \print" your plot to a le instead of the printer.
8.9 Other Buttons in The XVGR Window
Across the top of the xmgr window you will notice other buttons. These are: Re-Draw: Generally after you have modi ed a plot xmgr will automatically re-draw once you have clicked the Accept button. If this doesn't happen, click Re-draw with the left mouse button. You will also need to Re-draw if you have resized your window. Z: Zoom. E: Expand world. S: Shrink world. AS: Autoscale. AT: Auto-ticks. PU: Push current world. PO: Make top of stack the current world. L: Scroll left. R: Scroll right. U: Scroll up. D: Scroll Down. PZ: Push current world and enable zoom. CY: Cycle through the world stack.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
8.10 Editing your Data in XVGR
8{9
8.10 Editing your Data in XVGR will allow you to \massage" your data: 1. Edit to add, delete, or move points 2. Transformations to perform certain operations such as Integration, Regression, Fourier, Digital Filtering, etc... When you are done, select Files again to store your parameter le (unless you loaded one which has not been changed) and then give it a name under Write parameters. Exit by selecting
Compose
Exit
8.11 References, and Demo Unfortunately there is no reference to xmgr other than the man pages. For a brief demo of the program, type: % /usr/local/lib/xmgr/Demo
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
XMGR
Draft
8{10
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
Part II
MODULE II (1 cr)MATLAB & MATHEMATICA
Draft
Draft
Chapter 9
WEEK I; MATLAB: Basic Introduction 9.1 Background
9.1.1 What is MATLAB? MATLAB is an interactive, matrix-based system for scienti c and engineering calculations. Contrarily to programming languages, such as Fortran, C, or Basic you can solve complex numerical problems without actually writing a program. 2 MATLAB is an abbreviation for MATrix LABoratory. 3 MATLAB is the most widely used software package for interactive numeric computation, graphics, data analysis1. 1
9.1.2 Availability MATLAB is available in the CAD lab (PC/Windows version), as well as in the Bechtel Laboratory. 5 A relatively inexpensive Student Edition is available from Prentice Hall and can be purchased from the Bualo Chip.
4
9.1.3 Accessing MATLAB In the CAD Lab, Matlab is accesible within Windows. 7 In the Bechtel Lab, MATLAB is accesible through by clicking the left mouse button and then selecting MATLAB. Note that the program is licensed to run only on the server (bechtel). 6
1 Other
similar products include IDL, and MATHEMATICA for symbolic computations.
Draft
9{2
WEEK I; MATLAB: Basic Introduction
8 If you want to run the program dierently, you need to xhost + on your console rlogin bechtel To connect you to the server setenv DISPLAY yourmachine:0.0 To have the graphics 9
displayed on your workstation
To exit MATLAB, simply type exit or quit.
9.1.4 Help for help you can either type help sqrt (i.e. help command followed by the name of the function, or you may type lookfor square (similar to the man -k in Unix).
10
9.1.5 Basic Features When you run MATLAB, there will be one or more windows on your monitor. The command window is the primary one where you interact with MATLAB, and the MATLAB prompt will look like
11
>>
with a blinking cursor to the right. 12 Basic commands are shown in Table 9.1.
help demo who what clear computer bC exit quit
General help facility run demonstrations list variables in memory list M- les on disk clear workspace type of computer local abort exit MATLAB same as exit
Table 9.1: Basic Commands 13
MATLAB has also a few special characters, Table 9.2
9.1.6 Simple Math 14
To begin with, let us go through a simple example
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
9.1 Background
9{3
Draft
Special Characters = assignment statement [ used to form vectors and matrices ] see [ ( arithmetic expression precedence ) see ( . decimal point ... continue statement to next line , separate subscripts and function arguments ; end rows, suppress printing % comments : subscripting, vector generation ! execute operating system command Table 9.2: Special Characters >> 29+6 ans= 35 >> 21*2+5^2 ans= 67 >> force=10 force = 10 >> distance=5 distance= 5 >> moment=force*distance moment= 50 >>
Try now the following commands who, whos, clear, who. 15 The basic arithmetic operations are +
addition ; subtraction multiplication b power n or = left or right division Victor E. Saouma
7.2+9.6 11-92 2.9*4.5 2.6b 0.45 27=5=5n27
Computing Literacy for Undergraduate Engineering Students
Draft
9{4
WEEK I; MATLAB: Basic Introduction
9.1.7 Common Mathematical Functions 16
Common mathematical functions are shown in Table 9.3
9.1.8 Statements, Expressions and Variables MATLAB is an interprative language; the expressions you type are interpreted and evaluated. MATLAB statements are usually of the form variable = expression, or simply expression 18 Expressions are usually composed from operators, functions, and variable names. Evaluation of the expression produces (most often) a matrix, which is then displayed on the screen and assigned to the variable for future use. If the variable name and = sign are omitted, a variable ans (for answer) is automatically created to which the result is assigned. 19 A statement is normally terminated with the carriage return. However, a statement can be continued to the next line with three or more periods followed by a carriage return. On the other hand, several statements can be placed on a single line if separated by commas or semicolons. 17
a=2;b=4;c=-240;deltasq=b^2-4*a*c;delta=sqrt(deltasq) delta = 44 x1=(-b+delta)/(2*a) x1 = 10 x2=(-b-delta)... /(2*a) x2 = -12
If the last character of a statement is a semicolon, the printing is suppressed, but the assignment is carried out. This is essential in suppressing unwanted printing of intermediate results. 21 MATLAB is case-sensitive in the names of commands, functions, and variables. For example, Apples is dierent from APPLES. 20
9.1.9 Display Formats 22 23
All computations in MATLAB are performed in double precision. The format of the displayed output is shown in Table 9.4 Once invoked, the chosen format
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
9.1 Background
9{5 Elementary Math Functions abs absolute value or complex magnitude angle phase angle sqrt square root real real part imag imaginary part conj complex conjugate round round to nearest integer x round toward zero
oor round toward ;1 ceil round toward 1 sign signum function rem remainder exp exponential base e log natural logarithm log10 log base 10 Trigonometric Functions sin sine cos cosine tan tangent asin arcsine acos arccosine atan arctangent atan2 four quadrant arctangent sinh hyperbolic sine cosh hyperbolic cosine tanh hyperbolic tangent asinh hyperbolic arcsine acosh hyperbolic arccosine atanh hyperbolic arctangent Special Functions bessel bessel function gamma gamma function rat rational approximation erf error function inverf inverse error function ellipk complete elliptic integral of rst kind ellipj Jacobian elliptic integral Table 9.3: Common Mathematical Functions
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
9{6
WEEK I; MATLAB: Basic Introduction
Draft
format short format long format short e format long e format bank format + format rat format hex
default display 16 digits 5 digits plus exponent 16 digits plus exponent 2 decimal digits positive, negative or zero rational approximation hexadecimal
Table 9.4: Display Options remains in eect until changed. 24 The command format compact will suppress most blank lines allowing more information to be placed on the screen or page. It is independent of the other format commands. sqrt(pi) ans = 1.7725 format long ans ans = 1.77245385090552 format long e ans ans = 1.772453850905516e+000
9.1.10 Printing Text and Matrices 25
The disp command can be used to display both data and text
disp(pi);disp('University of Colorado') 3.1416 University of Colorado
Formatted output can be done through the fprintf command which provides you with better control on the format. It has two arguments: 1. Text and format speci cations which must be enclosed in a single quote. Within the text, the following speci er can be used:
26
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
9.1 Background
9{7 %e %f %g n
n
Exponential notation Fixed point or decimal notation Whichever is shorter New line
2. Matrix to be printed v=153.98; fprintf('Velocity is %f miles an hour',v) Velocity is 153.980000 miles an hourfprintf('Velocity is %f miles an hour\n',v) Velocity is 153.980000 miles an hour fprintf('Velocity is %e miles an hour\n',v) Velocity is 1.539800e+002 miles an hour fprintf('Velocity is %g miles an hour\n',v) Velocity is 153.98 miles an hour fprintf('Velocity is %8.3f miles an hour\n',v) Velocity is
27
153.980 miles an hour
Text and string operations, Table 9.5
abs eval num2str int2str setstr sprintf isstr strcomp hex2num
Text and Strings convert string to ASCII values evaluate text macro convert number to string convert integer to string set ag indicating matrix is a string convert number to string detect string variables compare string variables convert hex string to number
Table 9.5: Text and String Operations
9.1.11 Variables 28
Variables are case sensitive, can contain up to 19 characters, and must start with a letter.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
9{8 29
WEEK I; MATLAB: Basic Introduction
MATLAB has several special variables, Table 9.6.
ans eps pi i, j inf NaN clock date
ops nargin nargout
Special Variables answer when expression not assigned
oating point precision
p
;1 1
Not-a-Number wall clock date
oating point operation count number of function input arguments number of function output arguments Table 9.6: Special Variables
9.1.12 MATLAB Workspace 30 When one logs out or exits MATLAB all variables are lost. However, invoking the command save before exiting causes all variables to be written to a non-human-readable disk le named matlab.mat. When one later reenters MATLAB, the command load will restore the workspace
to its former state. 31 To recall previous commands, you can use the cursors keys. 32 MATLAB can execute a sequence of statements stored on disk les. Such les are called \M- les" because they must have the le type of .m as the last part of their lename. 33 There are two types of M- les: Script les are ASCII les which consist of a sequence of normal MATLAB statements. If the le has the lename, say, hw1.m, then the MATLAB command hw1 will cause the statements in the le to be executed. Script les can be edited by a standard editor. Script les can also be used to enter data into a large matrix; in such a le, entry errors can be easily edited out. An M- le can reference other M- les, including referencing itself recursively. Function les Function les provide extensibility to MATLAB. You can create new functions speci c to your problem which will then have the same status as other MATLAB functions.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
9.1 Background
9{9
9.1.13 Saving and Retrieving Data 34 If you want to save the variables in the fn command where fn is the le name. 35 36
workspace before you quit, you must use the save
To retrieve your data next time, load fn. Disk les commands are shown in Table 9.7
chdir delete diary dir load save type what fprintf pack
Disk Files change current directory delete le diary of the session directory of les on disk load variables from le save variables to le list function or le show M- les on disk write to a le compact memory via save
Table 9.7: Disk Files Commands
9.1.14 Arrays 37
Arrays can be entered in several dierent ways: Entered by an explicit list of elements, Generated by built-in statements and functions, Created in M- les, Loaded from external data les
38
The following session is self explanatory, study it in detail.
x=[2. 6. 12.] x = 2 6
12
y=[3. 5. 1.] y =
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
9{10
WEEK I; MATLAB: Basic Introduction 3
5
1
x.*y ans = 6
30
12
10 30 60
2 6 12
12
24
y' ans = 3 5 1 x*y' ans = 48 x'*y ans = 6 18 36 2*x ans = 4 x(2) ans = 6 x(1:2) ans = 2
6
x(3:-1:1) ans = 12
6
2
x=(0:0.1:1) x = Columns 1 through 7 0 0.1000 Columns 8 through 11 0.7000 0.8000
Victor E. Saouma
0.2000
0.3000
0.9000
1.0000
0.4000
0.5000
0.6000
Computing Literacy for Undergraduate Engineering Students
Draft
9.1 Background
9{11
linspace(0,pi,11) ans = Columns 1 through 7 0 0.3142 Columns 8 through 11 2.1991 2.5133 x=[2. 6. 12.] x = 2 6 x.^2 ans = 4 x=[1,2,3] x = 1
39
0.6283
0.9425
2.8274
3.1416
1.2566
1.5708
1.8850
12
36
144
2
3
Array operations are shown in Table 9.8 Element by Element Array Operations Operation Algebraic Form MATLAB Addition ai + bi a+b Substraction ai ; bi a;b Multiplication ai bi a: b Right division ai =bi a:=b Left division bi =ai a:nb b i Power ai a:^b Table 9.8: Array Operations
x=[6 2 4 8 -2 12];y=[2 6,3, 1 2,10] y = 2 6 3 1 2 10 size(y) ans = 1 6 x+y ans =
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
9{12
WEEK I; MATLAB: Basic Introduction 8
8
x.*y ans = 12 12 x./y ans = 3.0000 y.\x ans = 3.0000
7
9
0
22
12
8
-4
120
0.3333
1.3333
8.0000
-1.0000
1.2000
0.3333
1.3333
8.0000
-1.0000
1.2000
9.1.15 Graphics One of the major strength of MATLAB are its graphics capabilities. They are numerous, and only few will be explored at this early stage. 41 MATLAB can produce both planar plots and 3-D mesh surface plots. To preview some of these capabilities enter the command plotdemo. 42 The plot command creates linear x-y plots; if x and y are vectors of the same length, the command plot(x,y) opens a graphics window and draws an x-y plot of the elements of x versus the elements of y.
40
x=(0:0.1:10); y=sin(x).*exp(-x); plot(x,y) grid xlabel('time [s]') ylabel('Temperature [Deg. F]') print -deps2 plot1.eps
will generate the plot of Fig. 9.1 Note that as new commands are entered, the plot is immediately updated. 43 When in the graphics screen, pressing any key will return you to the command screen while the command shg (show graph) will then return you to the current graphics screen. If you are in the Bechtel Lab, then you can have multiple graphics windows. 44 The command grid will place grid lines on the current graph. 45 Graphs can be given titles, axes labeled, and text placed within the graph commands which take a string as an argument, Table 9.9. 46 To make multiple plots on a single graph x=0:0.1:2*pi;y1=sin(x);y2=cos(x);plot(x,y1,'-',x,y2,'-.');grid
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
9.1 Background
9{13
title xlabel ylabel gtext text
graph title x-axis label y-axis label interactively-positioned text position text at speci ed coordinates Graphs plot linear X-Y plot loglog loglog X-Y plot semilogx semi-log X-Y plot semilogy semi-log X-Y plot polar polar plot bar bar charts stairs stairstep graph errorbar add error bars Graph Annotation title plot title xlabel x-axis label ylabel y-axis label grid draw grid lines text arbitrarily position text gtext mouse-positioned text ginput graphics input Graph Window Control axis manual axis scaling hold hold plot on screen shg show graph window clg clear graph window subplot split graph window Table 9.9: 2D Graphics Commands
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
9{14
WEEK I; MATLAB: Basic Introduction
Draft
0.35
0.3
Temperature [Deg. F]
0.25
0.2
0.15
0.1
0.05
0
−0.05 0
1
2
3
4
5 time [s]
6
7
8
9
10
Figure 9.1: Simple Plot renders a dashed line and dashed dotted line for the rst and second graph respectively, resulting in Fig. 9.2 1 0.8 0.6 0.4 0.2 0 −0.2 −0.4 −0.6 −0.8 −1 0
1
2
3
4
5
6
7
Figure 9.2: Multiple Plots in a Single Graph Line colors can also be separately speci ed 48 The command subplot can be used to partition the screen so that up to four plots can be viewed simultaneously. 47
9.1.16 Graphics hardcopy 49 A hardcopy of the graphics screen can be most easily obtained with the MATLAB print which will print or save the graph (see example above). The syntax is
command
PRINT [ -ddevice] [ -options ]
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
9.2 Assignment
9{15
where the most common devices are shown in Table 9.10 dps PostScript for black and white printers dpsc PostScript for color printers dps2 Level 2 PostScript for black and white printers dpsc2 Level 2 PostScript for color printers deps Encapsulated PostScript (EPSF) depsc Encapsulated Color PostScript (EPSF) deps2 Encapsulated Level 2 PostScript (EPSF) depsc2 Encapsulated Level 2 Color PostScript (EPSF) dhpgl HPGL compatible with Hewlett-Packard 7475A plotter dljetplus HP LaserJet+ dljet3 HP LaserJet III dcdeskjet HP DeskJet 500C with 1 bit/pixel color dbj10e Canon BubbleJet BJ10e dgif8 8-bit color GIF le format Table 9.10: Printer Devices
9.2 Assignment 9.2.1 Practice
Start by repeating all the examples in this handout.
9.2.2 Work
The force F which moves a body along a straight line path S is the scalar product of F:S = W . In general we may either break down the path into a series of linear segments, or if the path is R curvilinear we must perform a line integral W = S F:dS . Given a force F with components (2,4,6), i.e. F = 2i + 4j + 6k, and the following points Point O A B C D E
Coordinates X Y Z 0 0 0 5 0 0 0 7 0 0 0 11 -200 -500 +1000 6 8 12
Determine the work for each of the following paths Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
9{16
Discuss your results.
WEEK I; MATLAB: Basic Introduction Case 1 2 3 4
Path O-A-B-C-E O-C-E O-D-E O-E
9.2.3 Stresses
If an in nitesimal element is subjected to the cartesian stresses shown below,
it can be shown that the stresses along any other orientation are given by: x1 = x +2 y + x ;2 y cos 2 + xy sin 2 x1y1 = ; x ;2 y sin 2 + xy cos 2 and the principal stresses are given by:
1;2 = x +2 y
s
(9.1-a) (9.1-b)
x ; y 2 + 2
(9.2) xy 2 For x = 12; 300 psi, y = ;4; 200 psi and xy = ;4; 700 psi, 1. Determine the stresses when the element is rotated by +30 degrees (counter-clockwise), 2. Determine the principal stresses 3. Plot the variation of all three stresses in terms of Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
9.2 Assignment
9{17
9.2.4 Measurement Errors, [1]
Let us consider an instrument with a scale graduated from 0-1000 (such as 0 to 1000 volts). If the instrument is guaranteed as belonging to the 3% class, the maximum error is 3% of the full-scale de ection, in this case 30. Hence, if the meter reads 500, the true value can be 30 100 = 6% Hence, anywhere in the range 470-530. The corresponding relative error equals 500 it is clear that the full scale de ection of the measuring instrument should not be much higher than the range of expected values. One frequently used rule of thumb is to havethe expected value between 1/2 and 2/3 of the full scale de ection. For this instrument 1. Calculate and display the per cent error for measured values in increments of 100. 2. Plot the percent error, against the measured values, in the interval 0-1000. Use intervals of 10.
9.2.5 Statistical Analysis; Part I 9.2.5.1 Elements of Statistics
Elementary statistics formulaes will be reviewed, as they are needed to properly understand structural reliability. 51 When a set of N values xi is clustered around a particular one, then it may be useful to characterize the set by a few numbers that are related to its moments (the sums of integer powers of the values): Mean: estimates the value around which the data clusters. 50
= N1
N X i=1
xi
(9.3)
it is the arithmetic average of all the data points. Expected Value: If data are not available, an expected value is assigned based on experience and judgment, and E (x) = x. Both the mean and the expected values are termed rst moment, and they correspond to the centroid of a probability density distribution. ( R1 = xf (x)dx Continuous systems E (x) = x = P;1 (9.4) N xf (x) Discrete systems i=1
Median: of a sorted series (xi;1 < xi < xi+1 ) is de ned as: xmed = Victor E. Saouma
(
x N2+1 N odd 1 (x N + x N ) N even 2 2 2 +1
(9.5)
Computing Literacy for Undergraduate Engineering Students
Draft
9{18
WEEK I; MATLAB: Basic Introduction
Variance: is an indication of the \width" of the cluster: 2 = N 1; 1 Ni=1 (xi ; )2 (9.6) or 2 = N1 Ni=1 (xi ; )2
(9.7)
Note that if N is less than 10, it is more appropriate to use the second equation, otherwise use the rst one. Standard Deviation: is de ned as the square root of the Variance
p
= 2
(9.8)
Coecient of Variation: is the standard deviation normalized with respect to the mean: V =
(9.9)
When insucient data are available to accurately compute the moments, the coecient of variation is often estimated on the basis of experience. Covariance: Pairs of random variables may be correlated or independent. If correlated, then the likelihood of y depends on the likelihood of x. Thus, covariance xy measures the combined eect of how two variables vary together.
xy = N1
N X i=1
(xi ; x)(yi ; y )
(9.10)
Correlation Coecient: xy is a nondimentional measure of the degree of correlation xy = xy
x y
(9.11)
A correlation coecient of 1:0 or ;1:0 indicates a perfect linear correlation. A positive value indicates that the variables either increase or decrease together, a negative one indicates that one value increases while the other decreases. A zero value indicates that there is no linear correlation between the variables.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
9.2 Assignment
9{19
Skewness: characterizes the degree of asymmetry of a distribution around its mean. It is de ned in a non-dimensional value. A positive one signi es a distribution with an asymmetric tail extending out toward more positive x 3 (9.12) Skew = 1 N xi ;
N i=1
Kurtosis: is a nondimensional quantity which measures the \ atness" or \peakedness" of a
distribution. It is normalized with respect to the curvature of a normal distribution. Hence a negative value would result from a distribution resembling a loaf of bread, while a positive one would be induced by a sharp peak: 4 Kurt = 1 N xi ; ; 3 (9.13)
N i=1
the ;3 term makes the value zero for a normal distribution. The expected value (or mean), standard deviation and coecient of variation are interdependent: knowing any two, we can determine the third. 53 Distribution of variables can be mathematically represented. 54 A Uniform distribution implies that any value between xmin and xmax is equaly likely to occur. 55 The general normal (or Gauss) distribution is given by, Fig. 9.3: 52
(x) = p 1 e; 21 [ 2 56
x; ]2
(9.14)
A normal distribution N (; 2 ) can be normalized by de ning
y = x ;
(9.15)
y2 (y) = p1 e; 2 2
(9.16)
and y would have a distribution N (0; 1):
The normal distribution has been found to be an excellent approximation to a large class of distributions, and has some very desirable mathematical properties: 1. f (x) is symmetric with respect to the mean . 57
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
WEEK I; MATLAB: Basic Introduction
−3.0 −2.5 −2.0 −1.5 −1.0 −0.5 0.0 0.40
0.5
1.0
1.5
2.0
2.5
3.0
0.5
1.0
1.5
2.0
2.5
3.0
0.5
1.0
1.5
2.0
2.5
3.0
0.35 0.30
2σ
PDF
0.25 0.20 0.15 0.10 0.05
0.00 −3.0 −2.5 −2.0 −1.5 −1.0 −0.5 0.0 µ 1.0 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 0.0 −3.0 −2.5 −2.0 −1.5 −1.0 −0.5 0.0 x
CDF
Draft
9{20
Figure 9.3: Normalized Gauss Distribution, and Cumulative Distribution Function 2. f (x) is a \bell curve" with in ection points at x = . 3. f (x) is a valid probability distribution function as: Z
1 f (x) = 1 ;1
4. The probability that xmin < x < xmax is given by:
P (xmin < x < xmax ) =
Z
(9.17) xmax
xmin
f (x)dx
5. Cumulative distribution functions (cdf) of the normal distribution de ned as: Z s x; 2 1 e; 12 [ ] dx (s) = p 2 ;1 and is expressed in terms of the error function (erf). 6. The cdf of normalized normal distribution function is given by: Z s 2 (s) = p1 e; x2 dx 2 ;1 and is usually tabulated in books. Victor E. Saouma
(9.18) (9.19)
(9.20)
Computing Literacy for Undergraduate Engineering Students
Draft
9.2 Assignment
9{21
9.2.5.2 Assignment
1. Generate the data for a normal distribution with a mean of 100 and a standard deviation of 20 and plot the probability distribution function from the mean minus the standard deviation, to the mean plus the standard deviation. 2. Retrieve (through anonymous ftp to bechtel) the following two sets ftp/pub/Structures/cven4837/set1.da and ftp/pub/Structures/cven4837/set2.dat. Those sets contains results of concrete compressive strength fc0 for two dierent ready mix companies. (a) For each set determine the Mean, Standard Deviation, Coecient of variation, Skewness, and Kurtosis. (b) Plot the probability distribution function f (x) (based on a Normal Distribution), plotted from ; 4: to + 4: (c) Plot a histogram of the normalized strength (from the input le) with 20 bins. (d) Superimpose the two plots. Note This problem will be revisited later to: a) use MATLAB statistical functions, and b) Apply numerical integration for the evaluation of the probability of the stregth being below a certain value.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
WEEK I; MATLAB: Basic Introduction
Draft
9{22
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
Chapter 10
WEEK II; MATLAB: Matrix Algebra 10.1 Syntax
10.1.1 Matrix Operations 10.1.1.1 Matrix De nition 1
Matrices can be entered in several dierent ways: Entered by an explicit list of elements, or built from blocks. For example, A=[1 4 6; 2 1 8; -2 7 -9]; B = [A, ones(3,2); zeros(2,3), eye(2)]} will build a 5-by-5 matrix.
Generated by built-in statements and functions, Table 10.1. For example,
ones(m,n)
produces an m-by-n matrix of ones; if A is a matrix, then ones(A) produces a matrix of ones of the same size as A. If x is a vector, diag(x) is the diagonal matrix with x down the diagonal; if A is a square matrix, then diag(A) is a vector consisting of the diagonal of A. Created in M- les, Loaded from external data les
2
The following session is self explanatory,
x=[1,2;6,7] x = 1 2
10{2
WEEK II; MATLAB: Matrix Algebra
Draft
eye zeros ones diag triu tril rand hilb magic toeplitz
identity matrix matrix of zeros matrix of ones see below upper triangular part of a matrix lower triangular part of a matrix randomly generated matrix Hilbert matrix magic square see help toeplitz
Table 10.1: Built In Matrix De nition Functions 6 x=[1 2 3 4 5 6 9 10 11] x = 1 4 9
7
2 5 10
3 6 11
\colon operation" is a much more eective way to deal with consecutive numbers than through loops (very slow). For instance
3
x=[3 -1 5] x = 3 -1
5
y=[x;x+1;2*x-1] y = 3 -1 4 0 5 -3
5 6 9
rot90(y) ans = 5 -1 3
6 0 4
9 -3 5
fliplr(y) ans = 5 -1 6 0 9 -3
3 4 5
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10.1 Syntax flipud(y) ans = 5 -3 4 0 3 -1
10{3 9 6 5
y(:,3) ans = 5 6 9 y(2,:) ans = 4
0
6
x(1,:) ans = 3
-1
5
z=[y(1,:);y(3,:)] z = 3 -1 5 5 -3 9 v=[0.2 1.4 2.6] v = 0.2000 1.4000
2.6000
diag(v) ans = 0.2000 0 0
0 0 2.6000
0 1.4000 0
10.1.1.2 Matrix Operations Matrix operations are listed in Table 10.2. 5 The \matrix division" operations deserve special comment. If A is an invertible square matrix and b is a compatible column, vector, then x = Anb is the solution of A x = b
4
>> A=[2 3;1 4];b=[8;9];AInv=inv(A); >> x=AInv*b x = 1 2 >> x=A\b
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
10{4
WEEK II; MATLAB: Matrix Algebra
Draft
+ addition ; subtraction multiplication b power 0 transpose n left division / right division Table 10.2: Matrix Operations x = 1 2
10.1.1.3 Matrix functions 6
Matrix built in functions are listed in Table 10.3.
eig chol svd inv lu qr logm expm sqrtm poly det size norm cond rank
eigenvalues and eigenvectors cholesky factorization singular value decomposition inverse LU factorization QR factorization matrix logarithm matrix exponential matrix square root characteristic polynomial determinant size 1-norm, 2-norm, F-norm, 1-norm condition number in the 2-norm rank Table 10.3: Matrix Functions
EDU>> x=[4 2 3; 1 6 5;-2 5 10] x = 4 2 3 1 6 5
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10.1 Syntax -2
10{5
5
10
EDU>> y=inv(x) y = 0.2318 -0.0331 -0.1325 0.3046 0.1126 -0.1589 EDU>> x*y ans = 1.0000 0.0000 0.0000
-0.0530 -0.1126 0.1457
0 1.0000 0.0000
0.0000 0.0000 1.0000
2.0000 6.0000 -0.9167
3.0000 11.5000 -6.2917
EDU>> lux=lu(x) lux = 4.0000 2.0000 -0.2500 6.0000 0.5000 -0.9167
3.0000 11.5000 -6.2917
EDU>> triu(lux) ans = 4.0000 2.0000 0 6.0000 0 0
3.0000 11.5000 -6.2917
EDU>> tril(lux) ans = 4.0000 0 -0.2500 6.0000 0.5000 -0.9167
0 0 -6.2917
EDU>> tril(lux,-1) ans = 0 0 -0.2500 0 0.5000 -0.9167
0 0 0
EDU>> lu(x) ans = 4.0000 -0.2500 0.5000 EDU>> det(x) ans = 151
EDU>> diag(lux) ans = 4.0000 6.0000
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10{6
WEEK II; MATLAB: Matrix Algebra
-6.2917 EDU>> eig(x) ans = 4.4123 12.9438 2.6440 EDU>> x=[0.5 0.25;0.25 0.5] x = 0.5000 0.2500 0.2500 0.5000 EDU>> [V,D]=eig(x) V = 0.7071 0.7071 -0.7071 0.7071 D = 0.2500 0 0 0.7500 EDU>> x*V-V*D ans = 0 0 0 0
10.1.2 Graphics Revisited 10.1.2.1 Polar Plots
theta=0:pi/60:2*pi;r=2*(1-cos(theta));polar(theta,r);axis square print -deps2 polar.eps
resulting in Fig 10.1
10.1.2.2 3-D mesh plots. 7 Three dimensional mesh surface plots are drawn with the function mesh. mesh(z) creates a three-dimensional perspective plot of the elements of the
The command matrix z . The mesh surface is de ned by the z-coordinates of points above a rectangular grid in the x-y plane.
% Shape Functions for Quadrilateral Quadratic Elements X=-1:1/20:1; Y=X; YT=Y'; XT=X'; N8=0.5*(1-YT.*YT)*(1-X); meshc(X,Y,N8)
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
10.1 Syntax
10{7
Draft
90 4 120
60 3 2
150
30
1
180
0
330
210
240
300 270
Figure 10.1: Polar Plot of a Cardioid print -deps2 shap8-8.eps c=contour(X,Y,N8); clabel(c) print -deps2 shap8-8-c.eps
and the plots are shown in Fig. 10.2 1 0.1 0.8
1 0.6 0.4
0.8
0.4
0.6
0.2
0.4
0
0.2
−0.2
0.9
0.8
0.7 0.6
−0.4
0 1
0.3
1
0.5 0.5
0 0
−0.5
−0.5 −1
−1
−0.6
0.5
−0.8 −1 −1
0.2 −0.8
−0.6
−0.4
−0.2
0
0.2
0.4
0.6
0.8
1
Figure 10.2: Sample of Surface and Contour Plots
10.1.2.3 Animation 8 Animation can be achieved in MATLAB moviein and getframe commands.
(student's edition may not support it) through the
X=-1:1/5:1;
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10{8
WEEK II; MATLAB: Matrix Algebra
Y=X; YT=Y'; XT=X'; N8=0.5*(1-YT.*YT)*(1-X); k=0; M=moviein(11); % set up for 11 frames for fac=-5:1:5 % loop k=k+1; z=fac*N8; surf(X,Y,z); %axis off; axis([-1 1 -1 1 -5 5]) % freeze the axis to user specified values M(:,k)=getframe; % grab the frame into M end movie(M,10) % play back 10 times
will generate the animation of Fig. 10.3 5
0
−5 1 1
0.5 0.5
0 0
−0.5
−0.5 −1
−1
Figure 10.3: Picture Used for Animation Note that alternatively you may generate the image within a loop, and insert a pause after each one.
9
10.1.3 Data Analysis
10.1.3.1 Statistical analysis 10
Statistical analysis prede ned functions are shown in Table 10.4.
EDU>> x=rand(1,10) % generate a uniform distribution x = Columns 1 through 7
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
10.1 Syntax
10{9
Draft
max min mean median std sort sum prod cumsum cumprod di hist corrcoef cov cplxpair
maximum value minimum value mean value median value standard deviation sorting sum of elements product of elements cumulative sum of elements cumulative product of elements approximate derivatives histograms correlation coecients covariance matrix reorder into complex pairs
Table 10.4: Statistical Analysis Functions 0.2190 0.0470 Columns 8 through 10 0.8310 0.0346
0.6789
0.6793
0.9347
0.3835
0.5194
0.0535
EDU>> rand('seed',0) %set seed EDU>> rand('uniform') % specify a uniform random distribution EDU>> rand(1,10) ans = Columns 1 through 7 0.2190 0.0470 0.6789 0.6793 0.9347 0.3835 Columns 8 through 10 0.8310 0.0346 0.0535
0.5194
EDU>> rand('seed',0) % reset the seed EDU>> x=randn(1,100); %Generates random numbers with a normal distribution EDU>> hist(x,20) % Histogram with 20 bins EDU>> print -deps2 hist1.eps EDU>> mean(x) ans = 0.0507 EDU>> max(x) ans = 2.9432 EDU>> min(x) ans =
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10{10
WEEK II; MATLAB: Matrix Algebra
-2.0186 EDU>> median(x) ans = 0.0239 EDU>> sum(x) ans = 5.0730 EDU>> std(x) ans = 0.9979 EDU>> sort(x) ans = Columns 1 through 7 -2.0186 -1.8769 -1.7651 ............. Columns 99 through 100 2.3722 2.9432
-1.6984
-1.6853
-1.6237
-1.4921
where the le hist1.eps is shown in Fig. 10.4 14
12
10
8
6
4
2
0 −3
−2
−1
0
1
2
3
Figure 10.4: Histogram
10.1.3.2 Regression Analysis
The following example will generate data which approximately t y = 2x +10, and then through a linear regression determine the parameters. EDU>> x=[0:1:10]; EDU>> mnoise=0.5*rand(1,11) mnoise = Columns 1 through 7
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10.1 Syntax 0.0173 0.0267 Columns 8 through 11 0.2087 0.3434
10{11 0.2649
0.3356
0.2945
0.4652
0.0038
0.1917
0.0334
22.3609
24.0212
EDU>> bnoise=2*rand(1,11); EDU>> y=(2+mnoise).*x+10+bnoise % noisy y=2x+10 y = Columns 1 through 7 11.6923 13.0806 14.7136 18.3146 18.8474 Columns 8 through 11 26.9856 29.2720 30.7453 36.1243 EDU>> coef=polyfit(x,y,1)% get the coefficients coef = 2.3546 10.6048 EDU>> m=coef(1); b=coef(2); yfit=m*x+b;plot(x,yfit,x,y,'o'),title('Linear Regression'),grid EDU>> print -deps2 regres.eps EDU>>
where the le regres.eps is shown in Fig. 10.5. Linear Regression 40
35
30
25
20
15
10 0
1
2
3
4
5
6
7
8
9
10
Figure 10.5: Regression Analysis
10.1.3.3 Signal Processing 11
MATLAB has a library of very powerful signal processing functions, Table 10.5.
10.1.4 Control Flow 12
MATLAB programming is very simple and supports the DO, WHILE, and IF constructs.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
10{12
WEEK II; MATLAB: Matrix Algebra
Draft
abs angle conv corrcoef cov deconv t t2 it it2 tshift
complex magnitude phase angle convolution correlation coecients covariance deconvolution radix-2 fast Fourier transform two-dimensional FFT inverse fast Fourier transform inverse 2-D FFT FFT rearrangement
Table 10.5: Signal Processing Functions MATLAB provides ow control statements (such as DO, WHILE and IF) which operate like those in most computer languages. 14 Relations and logical operators in MATLAB are given in Table 10.6.
13
< > <= >=
less than greater than less than or equal greater than or equal == equal = not equal. & and j or not. Table 10.6: Relations and Logical Operators 15
Note that \=" is used in an assignment statement while \==" is used in a relation.
EDU>> x=4*rand(1,10); EDU>> for k=1:10 if x(k)>=3 disp('A') elseif x(k)<3 & x(k)>=2 disp('B') else disp(' You failed') end end
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10.1 Syntax
10{13
You failed B A You failed You failed A B A B
another example EDU>> max=10;x(1)=1;x(2)=1;k=3; EDU>> while k<max x(k)=x(k-1)+x(k-2); k=k+1; end EDU>> x x = 1 1 2 3 5
16
8
13
21
34
MATLAB has some prede ned relational and logical functions, Table 10.7.
any all nd isnan nite isempty isstr strcmp
logical conditions logical conditions nd array indices of logical values detect NaNs detect in nities detect empty matrices detect string variables compare string variables
Table 10.7: Relational and Logical Functions 17
Control ow is described through Table 10.8
10.1.5 Function Files Function les take one or more external arguments (enclosed in parenthesis) and return one or more output.
18
function hyp=pyt(a,b) % All commented lines following the function definition
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
10{14
WEEK II; MATLAB: Matrix Algebra
Draft
if elseif else end for while break return pause
conditionally execute statements used with if used with if terminate if, for, while repeat statements a number of times do while break out of for and while loops return from functions pause until key pressed Table 10.8: Control Flow
% will be displayed if the user types help pyt if nargin < 2 disp('invalid number of arguments'; end hyp=sqrt(a.^2+b.^2);
This le should be placed in a disk le with lename pyt.m (corresponding to the function name). The rst line declares the function name, input arguments, and output arguments; without this line the le would be a script le. Then a MATLAB statement c=hyp(4,5), for example, will cause the numbers 4 and 5 to be passed to the variables a and b in the function le with the output result being passed out to the variable c. Since variables in a function le are local, their names are independent of those in the current MATLAB environment. 20 Note that use of nargin (\number of input arguments") permits one to set a default value of an omitted input variable. 21 A function may also have multiple output arguments. For example:
19
function [mean, stdev] = stat(x) % STAT Mean and standard deviation [m n] = size(x); if m == 1 m = n; end mean = sum(x)/m; stdev = sqrt(sum(x.^2)/m - mean.^2);
Once this is placed in a disk le stat.m, a MATLAB command [xm, xd] = stat(x), for example, will assign the mean and standard deviation of the entries in the vector x to xm and xd, respectively. Single assignments can also be made with a function having multiple output arguments. For example, xm = stat(x) (no brackets needed around xm) will assign the mean of x to xm. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10.2 Assignment
10{15
10.2 Assignment 10.2.1 Practice
Start by repeating all the examples in this handout.
10.2.2 Polar Plot
Plot the following curve (Folium of Descartes) 3a sin cos r = sin 3 + cos3 for ;=6 =2, use a = 1.
(10.1)
10.2.3 Animation
The transverse vibration of an undamped simply supported beam straight beam is given by q
v = C2 sin nx L
(10.2)
EI4 Write a function which will accept as argument the mode at thee frequency !n = n2 2 mL shape (n which is an integer), the number of frames N and will generate an animation of the beam vibration. Let C2 vary from ;L=5 to L=5, and take L = 10.
10.2.4 Strain Rosette 10.2.4.1 Theory
Experimentally, strains are measured by a strain gage. The most common type of strain gage is the bonded resistance strain gage shown in Fig. 10.6. These gages use a grid of ne wire or a
Figure 10.6: Bonded Strain Gage metal foil grid encapsulated in a thin resin backing. The gage is glued to the carefully prepared test specimen by a thin layer of epoxy. The epoxy acts as the carrier matrix to transfer the Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10{16
WEEK II; MATLAB: Matrix Algebra
strain in the specimen to the strain gage. As the gage changes in length, the tiny wires either contract or elongate depending upon a tensile or compressive state of stress in the specimen. The cross sectional area will increase for compression and decrease in tension. Because the wire has an electrical resistance that is proportional to the inverse of the cross sectional area, R A1 , a measure of the change in resistance can be converted to arrive at the strain in the material. Bonded resistance strain gages are produced in a variety of sizes, patterns, and resistance. One type of gage that allows for the complete state of strain at a point in a plane to be determined is a strain gage rosette. It contains three gages aligned radially from a common point at dierent angles from each other, Fig. 10.7. The strain transformation equations to
Figure 10.7: Strain Rosette convert from the three strains at any angle to the strain at a point in a plane are
"a = "xx cos2 a + "yy sin2 a + xy sin a cos a "b = "xx cos2 b + "yy sin2 b + xy sin b cos b "c = "xx cos2 c + "yy sin2 c + xy sin c cos c
(10.3-a) (10.3-b) (10.3-c)
The angles are usually given by
b a b c c = b 0o 60o 120o c
(10.4)
When the measured strains a , b , and c , are measured at their corresponding angles from the reference axis and substituted into the above equations the state of strain at a point may be solved, namely, xx, yy , and xy . The stresses are in turn related to the strains through the elastic constants E and , Young's modulus and Poisson's ratio (lt0:5)respectively.
xx = (1;2E)(1+ ) [(1 ; )"xx + ("yy + "zz )] yy = (1;2E)(1+ ) [(1 ; )"yy + ("zz + "xx )] E xy xy = 2(1+ ) Victor E. Saouma
(10.5)
Computing Literacy for Undergraduate Engineering Students
Draft
10.2 Assignment
10{17
Those would de ne the stress tensor 2 6 4
xx xy xz xy yy yz xz yz zz
3
(10.6)
7 5
It can be shown that the solution for principal stresses, i.e. stresses acting on principal planes where there is no shear stress, yields
l(xx ; ) + mxy + nxz = 0 lxy + m(yy ; ) + nyz = 0 lxz + myz + n(zz ; ) = 0
(10.7-a) (10.7-b) (10.7-c)
where l, m and n are direction cosines. Since those are linear and homogeneous equations in l, m and n a solution will exist only if
or
xx ; xy xz xy yy ; yz = 0 xz yz zz ;
(10.8)
3 ; I1 2 ; I2 ; I 3 = 0
(10.9)
where I1 , I2 and I3 are three invariants equal to
I1 = xx + yy + zz I2 = xy2 + xz2 + yz2 ; xxyy ; xxzz ; yy zz xx xy xz I3 = xy yy yz xz yz zz
(10.10-a) (10.10-b) (10.10-c)
The three roots (1 ; 2 ; 3 ) are the three principal stresses. The direction cosines of the three principal axes are obtained from Eq. 10.7-a-?? by setting in turn equal to 1; 2 ; 3 and recalling that l2 + m2 + n2 = 1.
10.2.4.2 Assignment Write a function which accepts as input arguments: 1. "a "b and "c from a 60 degrees strain rosette. 2. Young's modulus and Poisson's ratio E , and . Determines 1. Cartesian strains (Eq. 10.3-a-10.3-c) Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10{18
WEEK II; MATLAB: Matrix Algebra
2. Stresses (Eq. 10.5) 3. Stress invariants (Eq. 10.10-a-10.10-c) 4. Principal stresses (through the eigenvalues in Eq. 10.8) 5. Direction cosines (Eq. ??; Tricky!). Test your program for the values shown in Table 10.9. Note that equal one microstrain
E "a a "b b "c c
Mild Steel Aluminum High Strength Concrete 30,000 ksi 70 GPa 31 GPa 0.30 0.33 0.20 600 2,000 -400 0 deg 0 deg 15 deg 500 1,500 -800 45 deg 120 deg 75 deg -200 -1,300 -1,200 90 deg 60 deg 135 deg Table 10.9: Strain Rosette Problems
(10;6 in/in)
10.2.5 Structural Design 10.2.5.1 Theory
The design of a steel truss entail the following steps: 1. Structural analysis in which the equations of equilibrium are applied at each node and written in terems of the unknown internal element forces and known externally applied load. This will result in a system of linear equations of the form [B] fxg = fPg
(10.11)
where fPg is the vector of externally applied load, and fxg the vector of unknown element forces (tension if positive, compression if negative). Note that the unknown vector contains both element forces ass well as reactions. 2. Analysis is performed for dierent loads, and then multiple load cases are coonsidered. Each load case is typically a linear combination of the basic load investigated. 3. Results (internal forces) are tabulated for all load cases, maximum forces determined, and each element is separately designed. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
10{19
Draft
10.2 Assignment
Figure 10.8: Steel Truss
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10{20
WEEK II; MATLAB: Matrix Algebra
10.2.5.2 Assignment
The truss shown in Fig. 16.1 is to be designed. The statics [B ] matrix can be assembled1 The resulting statics matrix which can be copied from ftp/pub/Structures/cven4837/truss.m is given by b=[... 1., 0. , 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.; ... 0., 1. , 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 1. , 0., 0.; ... 0., 0. , .82, 1. , 0., 0., 0., 0., 0., 0., 0., 0., ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.; ... 0., -1.,-.57, .08, 0., 0., 0., 0., 0., 0., 0., 0., ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.; ... -1., 0.,-.82, 0., 0. , 1. , 0., 0., 0., 0., 0., 0., ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.; ... 0., 0., .57, 0., 1. , 0. , 0., 0., 0., 0., 0., 0., ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.; ... 0., 0., 0., -1., 0. , 0.,-.77, 1. , 0., 0., 0., 0., ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.; ... 0., 0., 0.,-.08, -1., 0., .64, .08, 0., 0., 0., 0., ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.; ... 0., 0., 0., 0., 0., -1., .77, 0., 0. , 1. , 0., 0., ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.; ... 0., 0., 0., 0., 0., 0.,-.64, 0., 1. , 0. , 0., 0., ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.; ... 0., 0., 0., 0., 0., 0., 0.,-1. , 0. , 0.,.73 , 1., ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.; ... 0., 0., 0., 0., 0., 0., 0.,-.08, -1., 0.,-.68, .08, ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.; ... 0., 0., 0., 0., 0., 0., 0., 0., 0., -1.,-.73, 0., ... 0., 1. , 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.; ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0. ,.68 , 0., ... 1., 0. , 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.; ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., -1., ... 0., 0., .71, 1., 0., 0., 0., 0., 0., 0., 0., 0.; ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,-.08, ... -1., 0.,-.71,.08 , 0., 0., 0., 0., 0., 0., 0., 0.; ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., ... 0., -1.,-.71, 0., 0. , 1. , 0., 0., 0., 0., 0., 0.; ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., ... 0., 0. , .71, 0., 1. , 0. , 0., 0., 0., 0., 0., 0.; ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., ... 0., 0., 0., -1., 0. , 0.,.68 , 1.0, 0., 0., 0., 0.; ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., ... 0., 0., 0.,-.08, -1., 0.,-.74, .08, 0., 0., 0., 0.; ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., ... 0., 0., 0., 0., 0., -1.,-.68, 0., 0. , 0., 1. , 0.; ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., ... 0., 0., 0., 0., 0., 0. , .74, 0., 1. , 0., 0., 0.; ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., ... 0., 0., 0., 0., 0., 0., 0.,-1. , 0. , 0., 0., 1.; ... 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., ... 0., 0., 0., 0., 0., 0., 0.,-.08, -1., 0., 0., 0.]; r=-[0., 0., 0., -0.9, 0., 0., 0., -1.74, 0., 0., 0., -1.68,... 0., 0., 0., -1.68, 0., 0., 0., -1.68, 0., 0., 0., -0.84];
1 Note
that in assembling the matrix, each column corresponds to an unknown internal element force, or an external reaction. Each row corresponds to an equation of equilibrium.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10.2 Assignment s=-[0., 0., 0., l=-[0., 0., 0.,
0., 0., -2.57, 0., -4.8 , 0., 0., 0., 0., 0., 0., 0.,
10{21 0., 0., 0., 0.,
0., 0., -4.97, 0., -4.8 , 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., -4.8, ... 0., 0., -2.4]; 0., -6.4, 0., ... 0.,-6.15, 0., 0.];
The three load vectors (corresponding to roof, snow, and live loads) are: r=-[0., 0., 0., -0.9, 0., 0., 0., -1.74, 0., 0., 0., -1.68, 0., 0., 0., -1.68, 0., 0., 0., -1.68, 0., 0., 0., -0.84] s=-[0., 0., 0., -2.57, 0., 0., 0., -4.97, 0., 0., 0., -4.8, 0., 0., 0., -4.8 , 0., 0., 0., -4.8 , 0., 0., 0., -2.4] l=-[0., 0., 0., 0., 0., 0., 0., 0., 0., -6.4, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,-6.15, 0., 0.]
Write a MATLAB program which will 1. Read the statics matrix and the load vectors 2. Invert the statics matrix [B] 3. Solve for the roof, snow, and live load forces 4. Obtain the forces for each of the 3 following three load combinations Load Case Roof Live Snow 1 1.4 0 0 2 1.2 1.6 0.5 3 1.2 0.5 1.6 5. Determine the maximum load for each member 6. Select the cross sectional area of each member using allowable = 20 kips/in2 in compression and nal area of each member using allowable = 24 kips/in2 in tension. 7. Tabulate the results as shown in Table 16.1 plus an additional column showing the crosssectional area in in2. Note that Note that the actual results are given by Table 16.1.
10.2.6 Dynamic Response of a Linear Oscillator 10.2.6.1 Theory
Newton's Second Law states that
dmv = f dt
(10.12)
where m is the mass, v the velocity, t time, and f the force. for a constant mass (unlike a rocket) we have f = ma (10.13) Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10{22
WEEK II; MATLAB: Matrix Algebra Member 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
L0 ; L1 U0 ; L0 U0 ; L1 U0 ; U1 U1 ; L1 L1 ; L2 U1 ; L2 U1 ; U2 U2 ; L2 L2 ; L3 U2 ; L3 U2 ; U3 U3 ; L3 L3 ; L4 U3 ; L4 U3 ; U4 U4 ; L4 L4 ; L5 U4 ; L5 U4 ; U5 U5 ; L5
Load Load Cases Design Load Roof Snow Live 1 2 3 Compr. Tens. 0. 0. 0. 0. 0. 0. 0 0 -8.5 -24. -13. -12. -35. -55. -55. 0 12. 34. 20. 17. 52. 79. 0 79. -9.8 -28. -16. -14. -43. -65. -65. 0 -6.8 -20. -11. -9.6 -30. -45. -45. 0 9.8 28. 16. 14. 43. 65. 0. 65. 7.3 21. 16. 10. 38. 50. 0. 50. -15. -44. -29. -22. -72. -100. -100. 0 -4.6 -13. -3.9 -6.5 -14. -29. -29. 0 15. 44. 29. 22. 72. 100. 0 100. 4. 11. 5.2 5.6 15. 26. 0 26. -18. -52. -32. -26. -83. -120. -120. 0 -2.7 -7.8 -3.6 -3.8 -10. -18. -18. 0 18. 52. 32. 26. 83. 120. 0 120. 1.4 3.9 4.6 1.9 9.8 10. 0 10. -19. -55. -36. -27. -90. -130. -130. 0 -0.97 -2.8 -3.3 -1.4 -6.9 -7.3 -7.3 0 19. 55. 36. 27. 90. 130. 0 130. -0.89 -2.5 4.2 -1.2 5.1 -3.1 -3.1 5.1 -19. -53. -38. -26. -93. -130. -130. 0 0.66 1.9 3.1 0.92 6. 5.3 0 6. Table 10.10: Result of Truss Design
Figure 10.9: Single Degree of Freedom Oscillator Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10.2 Assignment
10{23
If we consider the linear oscillator shown in Fig. 10.9 setting up the sum of the horizontal forces we have mu + cu_ + ku = P sin !t (10.14) where u and u_ are the acceleration and velocity respectively, k the stiness of the spring, P sin !t the driving force. The solution to this problem is of the form
u = et
(10.15)
(m2 + c + k)et = P sin !t
(10.16)
and substituting into Eq. 10.14 we obtain Since the exponential is never equal to zero we have
p2 ; c c ; 4mk =
or If we de ne
2m
!1=2 1=2 1=2 2 c k k c = ; 2(km)1=2 m m 4km ; 1
(10.18)
s
k m Undamped natural frequency c Fraction of critical damping = pc = 2m! 2 km n
!n = then Eq. 10.14 becomes
A solution of this equation is where
(10.17)
(10.19-a) (10.19-b)
P sin !t u + 2!n u_ + !2 u = m
(10.20)
u = C1 sin !t ; C2 cos !t
(10.21)
1 ; (!=!n )2 C1 = Pk [1 ; (!=!n )2 ]2 + [2!=!n ]2 2!=!n C2 = Pk [1 ; (!=!n )2 ]2 + [2!=!n ]2 = tan;1 CC2 1
(10.22-a) (10.22-b) (10.22-c)
is the phase lag between the applied force, and the system response. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10{24
WEEK II; MATLAB: Matrix Algebra
We can also express the displacement, velocities and accelerations as
where
u = Pk Rd sin(!t ; ) u_ = pP Rv cos(!t ; ) km P u = ; m Ra sin(!t ; )
1 [1 ; (!=!n )2 ]2 + [2!=!n ]2
Rd =
q
Rv =
q
!=!n
[1 ; (!=!n )2 ]2 + [2!=!n ]2 (!=!n)2 Ra = q [1 ; (!=!n )2 ]2 + [2!=!n ]2
(10.23-a) (10.23-b) (10.23-c) (10.24-a) (10.24-b) (10.24-c) (10.24-d)
and correspond to the displacement, velocity and acceleration factors respectively.
10.2.6.2 Assignment 1. Generate surface plots showing (a) Rd in terms of 0 !=!n 3 and 0 1:2 (b) Rv in terms of 0 !=!n 3 and 0 5 (c) Ra in terms of 0 !=!n 3 and 0 5 (d) in terms of 0 !=!n 3 and 0 5 000 = 5:176 lb/in/sec2), is supported by a 60" cantilever with a 2. A 2,000 lbm (or (322:;2)(12) q p stiness k = 1; 065lb=in; The natural frequency is !n = mk = 1; 0655:176 = 14:34 rad/sec. An external force with an amplitude of 250 lb which oscillates at 3 cycles per second is applied. The excitation frequency is ! = 2f = 2(3:1416)(3) = 18:85 rad/sec. The system is damped to 2 percent of critical damping. Generate 4 plots (on the same display) showing the excitation force, displacement, velocity and accelerations for 0 t 5 sec.
10.2.7 Nonlinear Equation 10.2.7.1 Theory
Considering a beam-column subjected to axial and shear forces as well as a moment, Fig. 10.10, dv between the axis taking the moment about i for the beam segment and assuming the angle dx Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10.2 Assignment
10{25 w(x)
P
P x dx y,u
w
M
V+
i
P
V
δV δx dx
δv δx
P
dx
M+ δM δx dx
w
P
θi
P
i j
θj
P
dx
Figure 10.10: Simply Supported Beam Column; Dierential Segment; Eect of Axial Force P of the beam and the horizontal axis is small, leads to (dx)2 + V + dV dx ; P dv dx = 0 M ; M + dM dx + w (10.25) dx 2 dx dx neglecting the terms in dx2 which are small, and then dierentiating each term with respect to x, we obtain d2 M ; dV ; P d2 v = 0 (10.26) dx2 dx dx2 However, considering equilibrium in the y direction gives dV = ;w (10.27) dx
From beam theory, neglecting axial and shear deformations, we have
d2 v M = ;EI dx 2
(10.28)
Substituting Eq. 10.27 and 10.28 into 10.26, and assuming a beam of uniform cross section, we obtain 4 2 (10.29) EI d v4 ; P d v2 = w
dx
Victor E. Saouma
dx
Computing Literacy for Undergraduate Engineering Students
Draft
10{26
WEEK II; MATLAB: Matrix Algebra
P , the general solution of this fourth order dierential equation to any set of Introdcing k2 = EI boundary conditions is v = C1 sin kx + C2 cos kx + C3 x + C4 (10.30) If we consider a column with one end xed (at x = 0), and one end hinged (at x = L). The boundary conditions are
v = 0; v;xx = 0 atx = 0 v = 0; v;x = 0 atx = L These boundary conditions will yield C2 = C4 = 0, and sin kL ; kL cos kL = 0
(10.31) (10.32)
But since cos kL can not possibly be equal to zero, the preceding equation can be reduced to tan kL = kL
(10.33)
which is a transcendental algebraic equation and can only be solved numerically.
10.2.7.2 Assignment Write a MATLAB function to solve for the rst 5 roots of Eq. 10.33 by zooming into the intersection of the left hand side with the right hand side.
10.2.8 Newton Raphson Method 10.2.8.1 Theory
Given an equation f (x) = 0 with f (x) expandable in a Taylor's series about an initial guess value x0 , we can write f (x) = f (x0 ) + f 0 (x)(x ; x0) + = 0 (10.34) neglecting high order terms. From this equation we can obtain x = x0 ; ff0((xx0 )) (10.35) 0 or (10.36) xi+1 = xi ; ff0((xxi )) i
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
10.2 Assignment
10{27
10.2.8.2 Assignment Write a MATLAB program which will 1. Ask the user (through the input function) (a) Equation f (x) to be solved (b) First derivative of the equation f 0 (x) (c) Range of x for plotting (xmin and xmax). (d) Initial guess for the solution (e) Tolerance 2. Plot the equation for the speci ed range 3. Solve the equation within the speci ed tolerance 4. Display the root of the equation and the number of iterations. Test your program by solving Eq. 10.33 and compare the number of ops ( oating point operations) with the preceding solution.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
WEEK II; MATLAB: Matrix Algebra
Draft
10{28
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
Chapter 11
WEEK III; MATLAB: \Advanced" Topics 11.1 Background
11.1.1 Numerical Integration and Dierentiation R
The integration of ab F (x)dx is essentially based on passing a polynomial P (x) through given Rb values of F (x) and then use a P (x)dx as an approximation.
1
Z
b a
F (x)dx
Z
a
b
(11.1)
P (x)dx
2 Using P (x) = F (x) at n points, and recalling the properties of Lagrangian interpolation functions, we obtain
P (x) = l1 (x)F (x1 ) + l2 (x)F (x2 ) + + ln(x)F (xn ) n X = li (x)F (xi ) i=1
(11.2-a) (11.2-b)
11.1.1.1 Newton-Cotes Method In Newton-Cotes integration, it is assumed that the sampling points are equally spaced, Fig. 11.6, thus we de ne
3
Z
a
b
P (x)dx =
Z
n bX a i
li (x)dxF (xi ) =
n Z X i
b a
li(x)dxF (xi )
(11.3)
WEEK III; MATLAB: \Advanced" Topics
Draft
11{2
P(ξ) F(ξ)
b -1
0
ξ
1
a ξ
Figure 11.1: Newton-Cotes Numerical integration or
Approximation ab P (x)dx = R ni=1 Wi(n) F (xi ) (11.4) Wi(n) = ab li (x)dx = (b ; a)Ci(n) Weights where Ci(n) are the \weights" of the Newton-Cotes quadrature for numerical integration with n equally spaced sampling points. 4 newton-Cotes constants, and corresponding reminder are shown in Table 11.1, (Bathe 1982). R
P
n C0(n) C1(n) C2(n) C3(n) C4(n) 1 1 2 3 4 5
21 61 87 90
24 63 328 90
1 63 128 90
1 328 90
7 90
Error 10;1 (b ; a)3 F II (x) 10;3 (b ; a)5 F IV (x) 10;3 (b ; a)5 F IV (x) 10;6 (b ; a)7 F V I (x)
Table 11.1: Weights for Newton-Cotes Quadrature Formulas It can be shown that this method permits exact integration of polynomial of order n ; 1, and that if n is odd, then we can exactly integrate polynomials of order n. Hence we use in general odd values of n, 6 For n = 2 over [;1; 1], we select equally spaced points at x1 = ;1 and x2 = 1 to evaluate 5
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
11.1 Background
11{3
R1
;1 P (x)dx
P (x) l1 (x) l2 (x) W1(2) (2) W 2 R1 ;1 F (x)dx
= = = = =
P2
i=1 li (x)F (xi ) x;x2 = 1 (1 ; x) xx1;;xx2 2 1 = 1 (1 + x) 2 Rx2 ;x1 R
1 l1 (x)dx = 1 1 (1 ; x)dx = 1 2 R;1 1 1 (1 + x)dx = 1 l ( x ) dx = 2 1 ;1 R; P 1 P (x)dx = 2 2 W (2) F (xi ) = F (;1) + F (1) i=1 i ;1 1 R; 1
which is the trapezoidal rule 7 For n = 3 over [;1; 1], we select equally spaced points at x1 = ;1 x2 = 0, and x3 = 1, to R evaluate ;1 1 P (x)dx P (x) = P3i=1 li (x)F (xi ) l1 (x) = (x(x1 ;;xx22)()(xx1;;xx3 3) ) = 21 x(x ; 1) l2 (x) = (x(x2 ;;xx11)()(xx;2 ;xx3 )3 ) = ;(1 + x)(x ; 1) l3 (x) = (x(x3 ;;xx11)()(xx;3 ;xx2 )2 ) = 21 x(1 + x) R R W1(3) = R;11 l1 (x)dx = R12 ;1 1 x(x ; 1)dx = 13 W2(3) = R;1 1 l2 (x)dx = ;1R1 ;(1 + x)(x ; 1)dx = 34 (3) = 1 l (x)dx = 1 1 x(1 + x)dx = 1 W 3 13 2 ;1 (3) 3 R1 R; P 1 3 W F (xi ) = 1 [F (;1) + 4F (0) + F (1)] F ( x ) dx P ( x ) dx = i =1 i ;1 ;1 3 which is Simpson's rule
11.1.1.2 MATLAB Examples MATLAB's functions for numerical (de nite) integration and dierentiation are shown in Table 11.2. Numerical Integration trapz trapezoidal numerical integration quad numerical function integration; Simpson's rule quad8 Newton-Cotes 8 panel rule di approximate derivatives
8
Table 11.2: Numerical Integration and Dierentiation 9
For example, let us recall the expression for the center of gravity Z
ydA y= A Victor E. Saouma
(11.5)
Computing Literacy for Undergraduate Engineering Students
Draft
11{4 and moment of inertia
WEEK III; MATLAB: \Advanced" Topics Z
Z
y2 dA
Iyy = x2 dA A Iyy = Iyycg + Ad2x
Ixx = A cg + Ad2 Ixx = Ixx y
(11.6-a) (11.6-b)
and moment of inertia for a given cross section for a rectangular cross (width b, height h) section we would have Z
ydA A Z h b ydy 0 = bh = h
y =
(11.7-a) (11.7-b)
(11.7-c) 2 Determining the moment of inertia Ixx with respect to the neutral axis (which passes through the centroid)
Ixx =
Z
A
y2 dA
Z
= 2b
h=2 2 y dy
0
(11.8-a) (11.8-b)
3 = bh (11.8-c) 12 We now seek to determine the centroid of the triangular cross section shown in Fig. 11.2 where A(;2; 0), B (4; 0) and C (0; 6) First we need to de ne the following functions (note that each one of them must be in a separate le). function y=line1(x) xx=[-2 0];yy=[0,6];coef=polyfit(xx,yy,1); y=coef(1).*x+coef(2); function y=line1x(x) xx=[-2 0];yy=[0 6];coef=polyfit(xx,yy,1); y=coef(1).*x.*x+coef(2).*x; function x=line1y(y) xx=[-2 0];yy=[0,6];coef=polyfit(yy,xx,1); x=-(coef(1).*y.*y+coef(2).*y); function y=line2(x)
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
11.1 Background
11{5
6
y
C
C.G. u
A
x
B
Figure 11.2: Center of Gravity and Moments of Inertia of A Triangular Cross-Section xx=[0 4];yy=[6 0];coef=polyfit(xx,yy,1); y=coef(1).*x+coef(2); function y=line2x(x) xx=[0 4];yy=[6 0];coef=polyfit(xx,yy,1); y=coef(1).*x.*x+coef(2).*x; function x=line2y(y) xx=[0 4];yy=[6 0];coef=polyfit(yy,xx,1); x=-(coef(1).*y.*y+coef(2).*y);
and now the following function will determine the areas and coordinates of the centroid a1=quad('line1',-2,0) cgx1=quad('line1x',-2,0)/a1 cgy1=quad('line1y',0,6)/a1 a2=quad('line2',0,4) cgx2=quad('line2x',0,4)/a2 cgy2=-(quad('line2y',0,6)/a2) a=a1+a2 cgx=(quad('line1x',-2,0)+quad('line2x',0,4))/a
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
11{6
WEEK III; MATLAB: \Advanced" Topics
cgy=(quad('line1y',0,6)-quad('line2y',0,6))/a
11.1.2 Nonlinear Equations and Optimization Nonlinear Equations and Optimization
fmin minimum of a function of one variable fmins minimum of a multivariable function fsolve solution of a system of nonlinear equations fzero
(zeros of a multivariable function) zero of a function of one variable
Table 11.3: Nonlinear Equations and Optimization
11.1.3 Ordinary Dierential Equations
The solution of ordinary dierential equations (ODE) can always be reduced to the study of sets of rst order dierential equations. For example
d2y + q(x) dy = r(x) dx2 dx
(11.9)
can be rewritten as two sets of rst order equations
dy dx = z(x) dz = r(x) ; q(x)z (x) dx
(11.10) (11.11)
where z is a new variable. Hence, all problems in ordinary dierential equations are reduced to the study of a set of n coupled rst order dierential equations for the function yi, i = 1; 2; ; n with the general form dyi(x) = f (x; y ; ; y ) i = 1; ; n (11.12) 1 n dx
where the functions fi are known derivatives of the y0 s and the x0 s are the independent variables. This is known as the Cauchy form and can be rewritten as
y10 (x) = f1(x; y) yn0 (x) = fn(x; y)
(11.13) (11.14)
where n corresponds to the order of the ODE. In order to solve the dierential equation, we also need to have its initial (or boundary) values. The simplest method to solve for yn+1 is the Euler method through
yn+1 = yn + hf (xn ; yn ) + O(h2 )
Victor E. Saouma
(11.15)
Computing Literacy for Undergraduate Engineering Students
Draft
11.1 Background
11{7
where xn+1 xn + h, and in which a linear approximation is made by using the rst two terms of the Taylor's series expansion. We observe that the formula is unsymmetrical (it advances the solution by h but uses the derivative only at the beginning of that interval). One can improve on Euler's method by Midpoint method where the derivative is taken at midpoint rather than at the beginning of the step, Fig. 11.3.
g1 = f (xn ; yn) yn+ 21 = yn + h2 g1 g = f x + h; y 2
n
yn+1 = yn + hg2
:
2 n+ 21
(11.18) (11.19)
g2
slope = g1
yn
(11.16) (11.17)
yn+1
; ; ;slope = g
2
tn
h=2
-
h=2
tn+1
Figure 11.3: Runge's Midpoint Method
Trapezoid method where we consider the average values of the derivatives, Fig.11.4 g1 = f (xn; yn) g2 = f (xn + h; yn + hg1 ) yn+1 = yn + h2 (g1 + g2 ) + O(h3 )
(11.20) (11.21) (11.22)
hence, through the symmetrization the method is now second order1 . Actually, we have just derived the equations for the second-order Runge-Kutta method. For example if 1 A method
is conventionally called nth order if its error is O(hn+1 ).
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
11{8
WEEK III; MATLAB: \Advanced" Topics slope = g1
yn
XXXz g2 yn+1
g 1 : slope = g1 +g2 2
tn
h
tn+1
Figure 11.4: Runge's Trapezoid Method
dy = x2 + y(x)2 , then xn = 2, yn = 1, h = 0:1 and the dierential equation is dx g1 = x2n + yn2 = 5 g2 = (tn + h)2 + (yn + hg1 )2 = 2:12 + 1:52 = 6:66 yn+1 = yn + h g1 +2 g2 = 1 + 0:1(5:83) = 1:583
(11.23) (11.24) (11.25)
Fourth-Order Runge-Kutta method is given by, Fig. 11.5. g1 = f (xn; yn) g2 = f (xn + h2 ; yn + h2 g1 ) g = f (x + h ; y + h g )
3 n 2 n 2 2 g4 = f (xn +h; yn + g3 ) yn+1 = yn + h g61 + g32 + g33 + g64 + O(h5 )
and it will require four evaluations of the right hand side per step h Fourth-Order Runge-Kutta method is given by g1 = f (xn; yn) g2 = f (xn + h2 ; yn + h2 g1 )
g3 = f (xn + h2 ; yn + h2 g2 ) g4 = f (xn +h; yn + hg3 ) yn+1 = yn + h g61 + g32 + g33 + g64 + O(h5 )
Victor E. Saouma
(11.26) (11.27) (11.28) (11.29) (11.30)
(11.31) (11.32) (11.33) (11.34) (11.35)
Computing Literacy for Undergraduate Engineering Students
Draft
11.1 Background
11{9
g : 2
slope = g1
yn
; ; ;
XXX z
-
tn
g g g ynslope +1 = 61 + 32 + 64
g3
h=2
PPPq g 4 h=2
tn+1
Figure 11.5: 4th Order Runge-Kutta Method
and it will require four evaluations of the right hand side per step h. Note, in many applications x corresponds to the time t, and thus Equation 11.12 can be rewritten as: dxi (t) = f (t; x ; ; x ) i = 1; ; n (11.36)
dt
1
n
dy = 1 + y(x)2 with y(0) = 0, As an illustrative example, let us consider the following ODE dx we seek y(=4), and stepsize h = =4 ' 0:78540 y0 = 0 g1 = 1 h y0 + 2 g1 = 0:39270 g2 = 1:1542 (11.37) y0 + h2 g2 = 0:45326 g3 = 1:2054 h y0 + 2 g3 = 0:94676 g2 = 1:8963 y1 = 0:99687 10
11
In this other example, let us consider the following second order ordinary dierential equation
d2 y = y dy (0) = 0 y (0) = 1 2 t dt e + 1 dt
(11.38)
we use t = 0:1and solve for the rst step only. But rst we transform it into two coupled equations
z = dy dt dz = y dt et + 1 z (0) = 1 dy = z y(0) = 1 dt
Victor E. Saouma
(11.39-a) (11.39-b) (11.39-c)
Computing Literacy for Undergraduate Engineering Students
Draft
11{10
WEEK III; MATLAB: \Advanced" Topics
For the rst step y0 = 1 and z0 = 0 and we seek y1 and z1 . We treat the dependent variables and their derivatives as vectors and each component of each vector must be calculated before proceding. Hence, g1 (y; z; t) = ety+1 ; g2 (y; z; t) = z; (11.40) are components of (g1 and g2 ) the derivative vector ~g . Now we can start by evaluating ~g at (y0 ; z0 ; t0 ). g11 (y0 ; z0 ; t0 ) = e0y+1 = 0:5 (11.41) g 2 (y ; z ; t ) = 0 1 0 0 0
Solve for the locations of the intermediary point z1=2 = z0 + 2t g11 (y0 ; z0 ; t0 ) = 0 + 02:1 (0:5) = 0:025 (11.42) y1=2 = y0 + 2t g12 (y0; z0 ; t0 ) = 1 + 02:1 (0) = 1 Derivatives g21 (y1=2 ; z1=2 ; t1=2 ) = e0:051 +1 = 0:487503 (11.43) g22 (y1=2 ; z1=2 ; t1=2 ) = z1=2 = 0:025 compute again the dependent variables z1=2 = z0 + 2t g21 (y1=2 ; z1=2 ; t1=2 ) = 0 + 02:1 (0:487503) = 0:024375 (11.44) y1=2 = y0 + 2t g22 (y1=2 ; z1=2 ; t1=2 ) = 1 + 02:1 ((0:025) = 1:001250 Derivatives g31 (y1=2 ; z1=2 ; t1=2 ) = 1e:0001250 :05 +1 = 0:488112 (11.45) 2 g3 (y1=2 ; z1=2 ; t1=2 ) = z1=2 = 0:024375 Dependent variables z1 = z0 + tg31(y1=2 ; z1=2 ; t1=2 ) = 0 + (0:1)(0:488112) = 0:048811 (11.46) y1 = y0 + tg32 (y1=2 ; z1=2 ; t1=2 ) = 1 + (0:1)(0:024375) = 1:002438 Derivatives g41 (y1 ; z1 ; t1 ) = 1e:002438 0:1 +1 = 0:476179 (11.47) g42 (y1 ; z1 ; t1 ) = z1 = 0:048811 First step is now completed, solve for z1 and y1 z1 = z0 + t 16 g11 (y0; z0 ; t0 ) + 31 g21 (y1=2 ; z1=2 ; t1=2 ) + 13 g31 (y1=2 ; z1=2 ; t1=2 ) + 16 g41 (y1;(11.48-a) z1 ; t1 ) = 0 + 0:1 61 (0:5) + 13 (0:487503) + 31 (0:488112) + 16 (0:476179) (11.48-b) = 0:048790 (11.48-c) 1 1 1 1 2 2 2 2 y1 = y0 + t 6 g1 (y0 ; z0 ; t0 ) + 3 g2 (y1=2 ; z1=2 ; t1=2 ) + 3 g3 (y1=2 ; z1=2 ; t1=2 ) + 6 g4 (y1 ;(11.48-d) z1 ; t1 ) (11.48-e) = 0 + 0:1 61 (0) + 13 (0:0:025) + 13 (0:0:024375) + 61 (0:048811) (11.48-f) = 1:002459
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
11.1 Background
11{11
There are two MATLAB functions for the solution of a system of ordinary dierential equations, Table 11.4. 12
Dierential Equations ode23 2nd/3rd order Runge-Kutta method ode45 4th/5th order Runge-Kutta-Fehlberg method Table 11.4: Dierential Equations As An illustrative example, let us reconsider the mass-spring-damper system previously analyzed in Sect. 10.2.6.1, the governing dierential equation was given by Eq. 10.14 mx + cx_ + kx = P sin !t (11.49) we now seek to rearrange this equation in Cauchy form suitable for the Runge-Kutta MATLAB solution. 9 x = ; mc x_ ; mk x + P sin !t > = y10 = ; mc y1 ; mk y2 + P sin !t (11.50) y1 = x_ 0 > ; y2 = y1 y = x
13
2
the initial boundary conditions are x = 0 and x_ = 0 or y1 (0) = 0 (11.51) y2 (0) = 0 (11.52) To analyze this problem with MATLAB we rst need to de ne an M- le which we call msd.m function yp=msd(t,y) % This function defines the differential equations, written in Cauchy % form, governing the response of a damped mass-spring system subjected % to a harmonic excitation. % Assign constants p= 2250.; % lbf m= 2000.; % lbm c=250; % k= 1065; % lb/in omega= 120.; % radiands % Initialize the yd matrix [rows, cols]=size(y); yp=zeros(rows,cols); % define the derivatives yp(1)=-c/m*y(1)-k/m*y(2)+p/m*sin(omega*t); yp(2)=y(1);
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
WEEK III; MATLAB: \Advanced" Topics
Now, to see how the system oscillates, we de ne the initial boundary values t0=0.;y0=[0.;0.]; tf=100;
and then the simulation is run through t0=0.;y0=[0.;0.]; tf=30; [t,y]=ode23('msd',t0,tf,y0); plot(t,y(:,2)),grid % Note that x corresponds to y(2) xlabel('Time, t [sec]') ylabel('Displacement, x [mm]') pause plot(y(:,1),y(:,2)) xlabel('Velocity') ylabel('Displacement')
Which will generate Figs. ?? 0.015
0.015
0.01
0.01
0.005
0.005
Displacement
Displacemnt, x [in]
Draft
11{12
0
−0.005
−0.01 0
0
−0.005
5
10
15 Time, t [sec]
20
25
30
−0.01 −0.02
−0.015
−0.01
−0.005
0 Velocity
0.005
0.01
0.015
0.02
Figure 11.6: Runge-Kutta Solution for the Mass-Spring-Damper System
11.2 Assignment 11.2.1 Practice
Start by repeating all the examples in this handout.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
11.2 Assignment
11{13
11.2.2 Probability
For the data set 1 of the rst homework (ftp/pub/Matlab/set1.dat), determine the probability that the concrete strength is between 3,950 psi and 4,050 psi using the following two approaches: 1. From the computed mean and standard deviation, use Eq. 9.18
P (xmin < x < xmax ) = where
Z
xmax
xmin
(x) = p 1 e; 12 [ 2
f (x)dx
x; ]2
(11.53) (11.54)
2. From the raw data. 3. Compare the two probabilities.
11.2.3 Moment of Inertias
Determine the Moment of inertias Ixx and Iyy for the triangular section of Fig. 11.2.
11.2.4 Reinforced Concrete Ultimate Stress Distribution
In reinforced concrete (r/c) beams, the strain distribution along the depth is assumed to be linearly varying, positive and negative at the lower and upper extreme bers respectively. At failure, the maximum compressive strain is 0.003. The stress-strain curve of (normal strength) concrete is nonlinear, hence the exact stress distribution is also nonlinear. In order to determine the ultimate load carrying capacity of a r/c beam, all we need is the resultant and location of the resultant force. Through extensive experimental studies, it was determined that a rectangular stress block, Fig. 11.7, would have the same resultant force F
F = 0| :85 f 0 ab {z }c |{z}
A
(11.55)
acting at a distance a=2 from the top where
a = 1 c 1 = 0:85
(11.56-a) (11.56-b)
In order to assess the accuracy of this equation, the following stress-strain curve was experimentally obtained fc0 2 "max = 2 " (11.57) " 1 + "max Using this equation, Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
WEEK III; MATLAB: \Advanced" Topics
Draft
11{14
Figure 11.7: Equivalent and Exact Stress Distribution in Reinforced Concrete Beams 1. Determine the resultant force and its location 2. Compare with the actual simpli ed approximation (where the resultant force is at a=2 fro the top and is equal to 0:85fc0 ab). Use: fc0 = 3; 000 lbs/in2, "max = 0:003, c = 4:in.
11.2.5 Mixture Problem, [2]
A 120 gallon tank contains 90 pounds of salt dissolved in 90 gallons of water. Brine containing 2 pounds of salt per gallon is owing into the tank at a rate of 4 gallons per minute. The mixture ows out of the tank at the rate of 3 gallons per minute. The dierential equation that speci es the amount of slat x(t) in pounds in the tank at time t is (11.58) x0 = 8 ; 90 3; t :x The tank is full after 30 minutes. 1. Determine and plot the amount of salt in the tank from time=0 until the tank is full. 2. Determine the amount of time required for the tank to contain 150 pounds of salt. 3. The analytical solution to the dierential equation is 4 (11.59) x(t) = 2(90 + t) ; (9090+ t)3 Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
11.2 Assignment
11{15
compare your numerical results with the exact ones.
11.2.6 Dog-Tracking, [1]
A number of interesting curves are trajectories of a point D moving at constant speed while always pointing toward another point M that moves along a known path. Such a method of tracking is known as dog-tracking because it resembles the path followed by a dog chasing his master. Similar curves are those followed by a vessel chasing another one, and by some ground-to-air or air-to-air missiles. Determine and plot the trajectories of a dog chasing his master for each of the following two cases: 1. The master moves on a straight line and (a) Initial dog position (x0 ; y0 )=(0,0) (b) Dog speed vd =10m/s (c) Master position at time t, xm = vm t, and ym =100m (d) Master speed vm =5m/s (e) Initial and nal times t0 = 0 and tf =10 s. 2. The dog is at the center of a circular pond of radius r while his master walks on the bank at constant velocity vm . The dog swims at a constant speed vd always toward his master and (a) Initial dog position (x0 ; y0 )=(0,0) (b) Dog speed vd =2.5m/s (c) Master speed vm =2m/s (d) Radius r = 15m ~ Hint: ~vd = vd jDM D~ M j , this will result into two separate equations (one for the x component and one for the y component).
11.2.7 Ballistic Model, [1]
A simple ballistic model assumes that only two forces act on a projectile, namely gravity and drag. According to this model, the equation of motion are (11.60-a) mvx0 = ;W vvx (11.60-b) mvy0 = ;W vvy ; mg where vx and vy are components of the velocity and v its magnitude. The drag W is given by (11.61) W = c v2 d2 w2
Victor E. Saouma
4
Computing Literacy for Undergraduate Engineering Students
Draft
11{16
WEEK III; MATLAB: \Advanced" Topics
where cw is the drag coecient and is nearly constant as long as the ight is at subsonic speed, is the air density, and d the diameter of the projectile. Plot the trajectory, using the following parameters: g=9.81 ms;2 , m=10 kg, cw =0.2, =1.225kgm;3 , d=0.005m. The initial conditions are x0=0m, y0 =0m, v0 =250 m/s and the gun elevation is =6, Use ode23 with a tolerance of 5:10;4 .
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
Chapter 12
Week IV: MATHEMATICA 12.1 Background 12.1.1 Introduction
12.1.1.1 What is Mathematica ? Mathematica is a program for symbolic mathematics. 2 With Mathematica, you can perform algebraic operations of various complexities. Hence, rather than numerically solving an Engineering problem, you can solve it algebraically. 3 Because of its power, Mathematica will enable you to easily address problem of such complexities that it would have been impractical to solve otherwise. 4 Finally, Mathematica has a very powerful set of graphics capabilities. 1
12.1.1.2 Availability Mathematica is available in the Bechtel Laboratory. 6 A relatively inexpensive Student Edition can be purchased from the Bualo Chip, and the University used to have a site license for it.
5
12.1.1.3 Front End and Kernel Mathematica consists of two parts: the Kernel which is the computation engine, and the Front End which is the user interface. The Kernel is identical on all computers, however the Kernel may vary. 8 There are two Front Ends supported in the Bechtel Lab:
7
Draft
12{2
Week IV: MATHEMATICA
Command-Line Interface: where the current input line is displayed on the last line of the
screen (it can be edited by using the arrow, insert and delete keys). This Front End does not support graphics, and is invoked by the math command. It is a convenient (and only available one) to use if you connect to the server via a remote terminal which does not support graphics (such as a home pc). Files storing Mathematica commands can be created by any ASCII editor and are usually given the le extension .m Notebook Front End: which can contain a mixture of text, graphics, and Mathematica definitions, Fig. 12.1. In this environment there is no need to use an external editor since the Notebook Front End plays also that role. Notebook les usually have a .ma or .mb for ASCII (to facilitate transfer to other computers) or binary les. 9
In both cases Mathematica is used interactively
12.1.1.4 Accessing Mathematica In the Bechtel Lab, Mathematica is accessible through by clicking the left mouse button and then selecting Mathematica. Note that the program is licensed to run only on the server (bechtel). 11 If you want to run the program dierently, you need to xhost + on your console rlogin bechtel To connect you to the server setenv DISPLAY yourmachine:0.0 To have the graphics displayed on your workstation Type math for the Command Line Front End. To exit you simply type Exit. 12 Alternatively, you may simply type mathematica for the Notebook Front End.
10
12.1.1.5 Help For help, simply type ?. For a speci c function, you can type ?Sqrt or ?P*. 14 Note that after each command, you should hit the following two keys simultaneously <Shift>
13
12.1.1.6 Notebook Front End 12.1.1.6.1 Pointers changes:
Victor E. Saouma
16
As the mouse moves around the Notebook, the shape of the pointer
Computing Literacy for Undergraduate Engineering Students
12{3
Draft
12.1 Background
Figure 12.1: Notebook Front End for Mathematica
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Week IV: MATHEMATICA
Draft
12{4
Figure 12.2: Notebook Front End Help for Mathematica
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
12.1 Background
12{5
Vertical I-bar appears when pointing to text (or input) that can be edited. If you click on
the mouse, the pointer will then blink. Horizontal I-bar appears when pointing to the space between two cells, or before the rst and after the last one. If you click the mouse, a horizontal line is drawn. Anything typed after will be part of a new cell. Cell-bracket Pointer appears when pointing to a cell bracket. If you click the mouse to select a group a cell (or group of cells), then you can copy the cell, paste something else into it, or re-execute the cell. If you double click, it will open or close the cell. Formatted-Cell Pointer appears when pointing to cells that are formatted (such as Mathematica output or graphics which can not be changed). Graphics Pointer appears when pointing inside the bounding box of a selected graphics. You can drag the graphic by depressing the mouse button and then moving the mouse. Sizing Pointers appears when pointing to handles of graphic's bounding box. Click and drag the mouse to rescale the graphic in the direction shown by the pointer. Watch Pointer Mathematica is busy can not be interrupted!.
12.1.1.6.2 Cell Brackets
17 A cell is the basic unit of organization in a Notebook. It can contain text, Mathematica input or output, or other cells. The style of the bracket in the right margin gives an indication of the cell attributes, and its size indicates its extent. Unformatted Cell contains ordinary text that can be edited such as Mathematica input or text. Inactive Cell can not be executed (such as Mathematica output, and they are usually formatted. Initialization Cell can be automatically evaluated when the Notebook is opened Locked Cell means that its content can not be altered unless it is rst unlocked. Closed Group implies that only the rst cell in the group is visible, and all others are not.
12.1.1.7 Brackets, Parentheses, and Braces Brackets are used to specify arguments of functions. Parenthesis are used for grouping. Without them, multiplication and division have a higher precedence than addition and subtraction. Braces are used to specify lists, vectors, and matrices.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
12{6
Week IV: MATHEMATICA
Double Brackets are used for indexing. Comments are enclosed by (* Comment *).
12.1.2 Examples
12.1.2.1 Basic Arithmetic Operation You can perform arithmetic operations with Mathematica as you would perform them with a pocket calculator: 1. Simple
18
In[1]:= 6 + 5 Out[1]= 11
2. or slightly more complex operations: In[2]:=6 ((3+4)^2-(5/6*7)+8 (9+10)) Out[2]=1171
The arguments of all Mathematica functions are enclosed in square brackets, and the names of built-in functions begin with capital letters. 3. and now try to do this on your calculator: In[1]:= 3^99 Out[1]= 171792506910670443678820376588540424234035840667
which is the exact value of 399 .
12.1.2.2 Approximate Numerical Values 19
You can use the Mathematica function N to get approximate numerical results.
= N[3^99] 47 Out[3]= 1.71793 10 In[4]:= 3^99//N 47 Out[4]= 1.71793 10
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
12.1 Background
12{7
12.1.2.3 Complex Numbers 20
Mathematica can also handle complex numbers: In[2]:= (2+5 I) (2-3 I) Out[2]= 19 + 4 I
12.1.2.4 Derivatives 21
Here is an example of a derivative.
In[1]:= D[x^2 Sin[a x],x] 2 Out[1]= a x
Cos[a x] + 2 x Sin[a x]
12.1.2.5 Integration In[1]:= Integrate[(x+y)^5,x] 6 4 2 3 3 2 4 x 5 5 x y 10 x y 5 x y 5 Out[1]= -- + x y + ------- + -------- + ------- + x y 6 2 3 2 In[2]:=
Integrate[Sin[x],{x,a,b}]
Out[2]= Cos[a] - Cos[b] In[3]:= Integrate[Sin[x]+Sin[y],{x,0,Pi/2},{y,0,x}] Pi Out[3]= -2 In[4]:= NIntegrate[Sin[x]^2-Sin[2 x],{x, 0,Pi}] Out[4]= 1.5708
12.1.2.6 Algebraic Formulae 22
Mathematica can expand or reduce mathematical expressions
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
12{8
Week IV: MATHEMATICA
In[5]:= Expand[(x+y)^5] 5 4 3 2 2 3 4 5 Out[5]= x + 5 x y + 10 x y, + 10 x y + 5 x y + y
12.1.2.7 Solving equations 23
Mathematica can determine the root of equations: In[15]:= Solve[x^2+3x-a==0,x] -3 + Sqrt[9 + 4 a] -3 - Sqrt[9 + 4 a] Out[15]= {{x -> ------------------}, {x -> ------------------}} 2 2
12.1.2.8 Matrices In[28]:= m=Table[(i),{i,9},{j,1}] Out[28]= {{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}} In[26]:= m=Table[(i+j),{i,0,8},{j,1}] Out[26]= {{1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}} In[29]:= m=Table[(i),{i,9},{j,2}] Out[29]= {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}, {7, 7}, {8, 8}, > {9, 9}}
Matrices are presented in Mathematica as a list of lists. Mathematica can add, multiply, determine the inverse, determinant, eigenvalues and eigenvectors of matrices:
24
In[37]:= m=Table[(j+i),{i,0,1},{j,2}] Out[37]= {{1, 2}, {2, 3}} In[41]:=Inverse[m] Out[40]= {{-3, 2}, {2, -1}}
or
In[40]:= Inverse[%37]
In[41]:= Det[%] Out[41]= -1 In[43]:= %37.%40 Out[43]= {{1, 0}, {0, 1}}
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
12.1 Background
12{9
In[44]:= a={{12,7,9},{4,3,1},{11,6,3}} Out[44]= {{12, 7, 9}, {4, 3, 1}, {11, 6, 3}} In[45]:= Inverse[a] 3 33 5 1 63 6 9 5 2 Out[45]= {{-(--), -(--), --}, {--, --, -(--)}, {--, -(--), -(--)}} 52 52 13 52 52 13 52 52 13 In[46]:= %2.%1 Out[46]= {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}} In[47]:= Eigenvalues[a]//N Out[47]= {20.4216, -3.21391, 0.79228} In[48]:= Det[a] Out[48]= -52
12.1.2.9 Graphics and Three-Dimensional Plots In[13]:= Plot[Sin[x],{x,0,2 Pi}] Out[13]= -Graphics-
In[10]:= Plot3D[Exp[x 2 y],{x,-2,2},{y,-2,2}] Out[10]= -SurfaceGraphics-
12.1.2.10 Interfacing with Mathematica 12.1.2.10.1 Input
25 Rather than typing all the input commands, you can store them in an ASCII le, the extension .m is recommended. To execute the le, simply type:
In[1]:= <<
where
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Week IV: MATHEMATICA
Draft
12{10
1
0.5
1
2
3
4
5
6
-0.5
-1
Figure 12.3: Two-dimensional Plot generated from Mathematica
1 0.5
2
0 1
-0.5 -1 -2
0 -1 0
-1 1
2
-2
Figure 12.4: Three-dimensional Plot generated from Mathematica Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
12.1 Background
Draft
12.1.2.10.2 Output
12{11 26
Mathematica can be interfaced
In[10]:= Integrate[x/(1+xsinx),x] 2 x Out[10]= ------------2 (1 + xsinx)
with: Mathematica Form
In[14]:= InputForm[%]
Out[14]//InputForm= x^2/(2*(1 + xsinx))
Fortran
In[12]:= FortranForm[%]
Out[12]//FortranForm= x**2/(2*(1 + xsinx))
C
In[11]:= CForm[%] Out[11]//CForm= Power(x,2)/(2*(1 + xsinx))
TEX
In[13]:= TeXForm[%] Out[13]//TeXForm= {{{x^2}}\over {2 \left( 1 + {\it xsinx} \right) }}
12.1.2.11 Packages Most function in Mathematica are written in C. However, some functions are written in Mathematica itself. Such functions are de ned in les called packages which will allow you to: 1. De ne a function or set of functions that are often used
27
2. Hide the implementation from the user 3. Save the functions and reload them when needed.
12.1.2.12 Graphics hardcopy The function PSPrint will generate a postscript le which can be later sent to the laser printer.
28
Type: PSPrint[%n]
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
12{12 29
Week IV: MATHEMATICA
If you want to save your graphics use the Mathematica command:
Display["file name",%n]
Where n is the number of your graphics output. Then in shelltool window use the ps x command to create a PostScript le.
12.1.2.13 Input le You can store all your operations into an ASCII le through a text editor, and then \load" it into Mathematica
30
See the {\it Mathematica} manuals for further info on input files.
12.1.3 Some Mathematica Commands 12.1.3.1 Basic Operations
Following are the basic operations supported by Mathematica Note that multiplication can be speci ed by either using an asterisk or by leaving a blank space between arguments. x^y power -x minus x/y devide x y z or x*y*z multiply x+y+z add 31
12.1.3.2 Mathematical Functions Following is a list of the most commonly used functions, a complete list is presented at the end of the chapter.
32
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
12.1 Background
12{13
Draft
Sqrt[x] Exp[x] Log[x] Log[b,x] Sin[x], Cos[x] Tan[x] ArcSin[x] ArcCos[x],ArcTan[x] n! Abs[x] Round[x] Mod[n, m] Random[ ] Max[x,y,..], Min[x,y,..] Grad[f] Div[f] Curl[f]
square root exponential natural logarithm logarithm to base b trigonometric functions (with arguments in radians) inverse trigonometric functions factorial (product of integers 1,2,...n) absolute value closest integer to x n modulo m (remainder on division of n by m) pseudorandom number between 0 and 1 maximum,minimum of x,y,... Gradient in the given system Divergence Curl
Note that all Mathematica built-in functions start with an upper case letter, and the arguments are enclosed in square brackets.
33
12.1.3.3 Some Mathematica Constants 34
Mathematica also has some physical constants hardwired into the system. Pi 3,14159 E 2.71828 Degree 3.14159/180:degrees to radians conversion factor p;1 I In nity 1
12.1.3.4 Complex Numbers x + Iy Re[z] Im[z] Conjugate[z] Abs[z] Arg[z]
Victor E. Saouma
The complex number x + i y Real part of z Imaginary part of z Complex conjugate of z Absolute value of z The argument phi in the exponential form of a complex number
Computing Literacy for Undergraduate Engineering Students
Draft
12{14
Week IV: MATHEMATICA
12.1.3.5 Recall of Previous Expressions
% Last result %% Next to last result % n Result on output line Out[n]
12.1.3.6 Assignment of Variables
x = value Assign value to x x = y = value Assign value to x and y x = . or Clear[x] Remove assignment of x
12.1.3.7 Brackets
(term) f[x] fa, b, cg v[[i]]
Parentheses for grouping Square brackets for functions Braces for lists Double brackets for indexing
12.1.3.8 Help
?name Display information on name ??name Display more information on name ?Aaaa* Display information on all commands whose names begin with C*
12.1.3.9 Interrupting Mathematica Continue Show Inspect Abort Exit
Victor E. Saouma
Continue calculation Show what MATHEMATICA is doing Inspect current state Abort this particular calculation Exit MATHEMATICA
Computing Literacy for Undergraduate Engineering Students
Draft
12.1 Background
12{15
12.1.3.10 Transformation of Algebraic Expressions Expand[expr]
Expand an expression into sum of terms Factor[expr] Write expr as a minimal product of factors Simplify[expr] Simplify expression Coecient[expr, form] Coecient of form in expr Numerator[expr] Numerator Denominator[expr] Denominator expr // Short Show one line outline of output Short[expr, n] Show n-line outline of result Eliminate[flhs1 == rhs1,lhs2 == rhs2, ...g, fx, ...g] Eliminate x, ... from the set of simultaneous equations Reduce[flhs1 == rhs1, lhs2 == rhs2, ...g, fx, y, ...g] Give a set of simpli ed equations, including all possible solutions
12.1.3.11 Dierentiation D[f, x] D[f, x1, x2, ...] D[f, fx, ng] Dt[f] Dt[f, x] Limit[f, x->xo]
Victor E. Saouma
Partial derivative of f with respect to x Multiple derivative of f with respect to x1, x2, ... The nth derivative of f with respect to x The total derivative of f The total derivative of f with respect to x The limit of f as x goes to xo
Computing Literacy for Undergraduate Engineering Students
Draft
12{16
Week IV: MATHEMATICA
12.1.3.12 Integration Integrate[f, x]
Inde nite integral of f with respect to x Integrate[f, fx, xmin, xmaxg] De nite integral of f wrt to x from xmin to xmax Integrate[f, fx, xmin, xmaxg, fy, ymin, ymaxg] Multiple integral of f with respect to y and x
12.1.3.13 Summation & Products Sum[f, fi, imin, imax, dig] Sum[f, fi, imin, imaxg, fj, jmin, jmaxg] Product[f, fi, imin, imaxg] fimaxg fi, imaxg fi, imin, imaxg fi, imin, imax, dig
12.1.3.14 Equations 12.1.3.14.1 Preliminaries
x=y x == y x != y x>y xy x
Summation with i incremented by di Nested summation of f with respect to j then i The product of f from imin to imax Iterate imax times without incrementation of a variable Increment i from 1 to imax by steps of 1 Increment i form imin to imax by steps of 1 Increment i from imin to imax by steps of di
Assigns the value of y to x Tests for x = y Unequal Greater than Greater than or equal to Less than Less than or equal to All equal All unequal not and or Execute then if p is true, else otherwise
12.1.3.14.2 Solution
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
12.1 Background
12{17
Solve[lhs == rhs, x] x /. expr expr1 /. expr2 Solve[flhs1 == rhs1, lhs2 == rhs2, ...g, fx, y, ...g]
Solve equation in terms of x Use expr to get values of x Use expr2 to get values for expr1 Solve simultaneous set of equations for x,y,...
12.1.3.14.3 Dierential Equations DSolve[eqns, y[x], x] Solve dierential equation for y[x], taking x as the independent variable DSolve[eqns, y, x] Give sol'n for y in pure functional form
12.1.3.14.4 Numerical Values N[expr] NIntegrate[f. fx, xmin, xmaxg] NSolve[lhs == rhs, x] NDSolve[eqns, y, fx, xmin, xmaxg]
12.1.3.15 Functions
Victor E. Saouma
Numerical value of expr Numerical approximation of integral Numerical approximation of the solution to the equation Solve numerically for y with independent variable x
f[x ] De ne the function f ?f Show de nition of f Clear[f] Clear de nition of f
Computing Literacy for Undergraduate Engineering Students
Draft
12{18
Week IV: MATHEMATICA
12.1.3.16 Vectors & Matrices fa, b, cg Vector (a,b,c) " # a b ffa,bg,fc,dgg Matrix c d Array[a, n] Range[n] Length[list] IdentityMatrix[n] MatrixForm[list] a. b cm Inverse[m] MatrixPower[m, n] Det[m] Transpose[m] Eigenvalues[m] Eigenvectors[m] Eigenvalues[N[m]] Eigenvectors[N[m]]
Build a length-n vector of the form fa[1],... Create a list f1, 2, 3, ..., ng Give number of elements in list Generate n x n identity matrix Display list in matrix form Matrix product Multiply a matrix by a scalar c Matrix inverse nth power of a matrix Determinant Transpose Eigenvalues Eigenvectors and Numerical eigenvalues Numerical eigenvectors
12.1.3.17 Graphics 12.1.3.17.1 Preliminaries Plot[f, fx, xmin, xmaxg] Plot f in terms of x from xmin to xmax Plot[Evaluate[f], fx, xmin, xmaxg First evaluate f then plot it 12.1.3.17.2 Plot Options
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
12.1 Background AspectRatio Axes AxesLabel AxesOrigin DefaultFont DisplayFunction Frame FrameLabel FrameTicks GridLines PlotLabel PlotRange Ticks Automatic None All True False PlotPoints MaxBend PlotDivision Show[plot] Show[plot, option->value] Show[plot1, plot2, ...]
12{19 Height-to-width ratio for plot Whether to include axes (True or False) Labels to be put on axes fxlabel, ylabelg or None Point at which axes cross The default font for text in the plot How to display graphics Whether to draw frame around plot Labels to be put around the frame What tick marks to draw if frame is included What grid lines to include An expression to be printed as a label for the plot Plot range of coordintes to include in the plot What tick marks to draw if there is an axes Use internal algorithms Do not include this Include everything Do this Do not do this Minimum number of points at which to sample the function Maximum kink angle between successive segments of a curve Maximum factor by which to subdivide in sampling the function Redraw a plot Redraw plot with changed options Combine several plots
12.1.3.17.3 3 Dimensional Plots Plot3D[f, fx, xmin, xmaxg, fy, ymin, ymaxg] Make 3D plot of f as a function of x and y 12.1.3.17.4 Parametric Plots
35
First you must load the ParametricPlot3D package:
In[1]:=<
ParametricPlot[ffx, fyg, ft, tmin, tmaxg] Make a parametric plot ParametricPlot[ffx, fyg, fgx, gyg, ft, tmin, tmaxg] Parametric plot of several curves simultaneously
12.1.3.17.5 File Manipulation <
Load an ASCII le containing Mathematica commands Output expr to an ASCII le Append expr to an ASCII le Display contents of an ASCII le Save de nitions for variables or Undergraduate functions in aEngineering le Computing Literacy for Students
Draft
12{20
Week IV: MATHEMATICA
12.1.3.17.6 Generating C, Fortran & TEXFiles
CForm[expr] Write expr as C code FortranForm[expr] Write expr as Fortran code TexForm[expr] Write expr in TEXform
12.1.4 Programming in Mathematica Programming in Mathematica is the process of writing functions, or packages, that can subsequently be executed by simply typing in the name of the package. Writing programs with Mathematica allows you to develop specialized functions in your eld of interest that can then be run from the Mathematica environment.
36
12.1.4.1 Building a Package The goal of writing a package is to make the new function behave as much like a Mathematica function as possible. This includes being able to type ?FunctionName for documentation on how to use the new package FunctionName. Also the output from the package should not be dependant on any previous calculations you have done during your Mathematica session. 38 Let's look at a few examples:
37
(*This function returns the first n powers of x*) PowerSum[x_,n_] := Block[{i}, Sum[x^i,{i,1,n}] ]
This would then be saved in a le with an extension .m, such as Example.m 1. PowerSum[ ] is the name of the function were are creating. 2. All the variables local to PowerSum[ ] are declared in a Block[ ] statement, this isolates them from any values they might hold globally. 3. For this example, you must make sure that you don't pass in variables that are used locally inside the function. For example:
39
In[1]:= <<Example.m In[2]:= PowerSum[x,5] Out[2]= x + x^2 + x^3 + x^4 + x^5
but if we were to call PowerSum with the following: Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
12.1 Background
12{21
In[3]:= PowerSum[i,5] Out[3]= 3413
notice that we get a number for our answer and not an expression. This is because the variable i, which we passed in, was captured by the variable (also called i) in the range of the summation. The following example shows how to avoid such a problem. PowerSum::usage = "PowerSum[x,n] returns the sum of first n powers of x." Begin["Private`"] PowerSum[x_,n_] := Block[{i}, Sum[x^i,{i,1,n}] ] End[]
40
Note we have done two things: 1. The usage statement de nes a help message to be printed out if the user types ?PowerSum. 2. The local variable i is now created in the context Private` which is not searched when you type in a variable name later on.
41
For example, with the revised Example.m you could type in the following:
In[1]:= <<Example.m In[2]:= PowerSum[i,5] Out[2]= i + i^2 + i^3 + i^4 + i^5
we now get the expression and not a numerical value.
12.1.4.2 A Complete Example Here is an example of a package that will plot a random walk of length n. It will start at the origin and then randomly choose a direction to follow for a line of length 1.
42
BeginPackage["RandomWalk`"] RandomWalk::usage = "RandomWalk[n] plots a random walk of length n." Begin["`Private`"] RandomWalk[n_Integer] := Block[{loc = {0.0,0.0}, dir, points = Table[0,{n+1}], range = N[{0, 2Pi}]}, points[[1]]=loc; Do[ dir = Random[Real,range]; loc += {Cos[dir],Sin[dir]}; points[[i]] = loc,
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
12{22
Week IV: MATHEMATICA {i,2,n+1}]; Show[ Graphics[{Point[{0,0}], Line[points]}], Frame->True, AspectRatio->Automatic]
] End[] EndPackage[]
The package is started by BeginPackage["RandomWalk`"] and ended by EndPackage[]. Once a package is complete these statements need to be inserted, but during development of the package it is suggested that they be left out. If they are included in the development stage they may interfere with the debugging process. Next is the usage statement followed by a short description of the package. This is the message that will be displayed when the user requests help for this command. The Begin["`Private`"] and End[] statements are to keep values of variables used outside the package from interfering with the variables used locally by the package. The RandomWalk[n Integer] := statement assigns the name RandomWalk and the parameter n (de ned as an integer) to the function. All the variable declarations and operations are done within the Block[........] statement. The rst part of Block[....] declares some variables: 1. loc = f0.0,0.0g de nes loc as a collection of two values, these will be used as x and y coordinates later on. 2. points is declared as a Table, see Mathematica reference for more details if you are not familiar with this command. Basically, points will be a list going from 0 to n+1. 3. range is exactly that, the N is to give an approximate value of Pi. The rst point of points is then assigned the origin. The semicolon at the end of the line is to separate statements. The next construct is a Do[...], this enable the user to iterate. The format is Do[statement , interator]. This Do loop has more than one statement, so they are separated by semicolons. The iterator is fi,2,n+1g. The following occur within the Do loop: 1. dir is chosen randomly from the range indicated in range and returned as a real. 2. loc is then assigned the cosine and sine of dir 3. points is assigned the value of loc. The next statements; Show[...], and Graphics[..], are straight forward Mathematica commands. For more information on these commands see the Mathematica reference text. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
12.2 Assignment
12{23
12.1.5 List of All Mathematica Functions Table 12.1 contains all Mathematica functions, with the most commonly used ones in boldfaced.
43
12.2 Assignment 12.2.1 Practice
Start by repeating all the examples in this handout.
12.2.2 Problems
Write a Mathematica Notebook to execute the following: 1. Solve x2 + 2x + 1 = 0 R Rp 2. Integrate 01 0 x yex2 dydx 3. Solve the following dierential equation y0 (x) = y(x) 4. Plot the function x sin x for x in the range [0; 6], and (a) Change the AspectRatio so that the width of the plot is twice its height. (b) Give the plot the label ``x Sin[x]''. (c) Label the x axis \x", and the y axis \y". 5. Plotsin( sin x + y) for ;3 < x < 3 and ;3 < y < 3 using 33 grid points, no display of the axes. 6. Generate a contour plot of the previous equation. p 7. Write a function which takes a pair x; y and returns x2 + y2 .
12.3 References 1. Wolfram, S. \Mathematica: A System for Doing Mathematics by Computer second edition, Addison-Wesley, 1991. 2. Maeder, R., Programming in Mathematica, Addison Wesley, 1991 3. Blachman, N., Mathematica a Practical Approach, Prentice Hall, 1991. 4. Gray, T., and Glynn J., The Beginner's Guide to Mathematica, Addison-Wesley, 1992. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
12{24
Week IV: MATHEMATICA
Above CoecientList EllipticK Headers yLightSources OneIdentity Re yCollect EllipticLog HermiteH yLighting OpenAppend Read Accumulate ColonForm Encode yHiddenSurf* Limit OpenRead ReadList Accuracy ColumnForm End Hide Line OpenTemporary ReadProtected AccuracyGoal Complement EndAdd Hold LineBreak OpenWrite Real yAddTo yComplex EndOfFile HoldAll LinearProgra* Operate Recall AiryAi ComplexIn ni* EndPackage HoldFirst LinearSolve Optional Rectangle AlgebraicRules Compose EndProcess HoldForm List Options yReduce AlgebraicRule* ComposeSeries EngineeringFo* HoldRest ListContourPl* Or Release Alias CompoundExp* Environment HorizontalForm ListDensityPl* Order Remove All Condition Epilog Hypergeometri* ListPlot OrderedQ Removed yAmbientLig* Conjugate Equal Hypergeometri* ListPlot3D Orderless RenderAll And Constant EquatedTo Hypergeometri* Listable Out R Apart Constants Erf Hypergeometri* Literal Outer RepeatedNull Append ConstrainedMax EulerE Hypergeometri* Locked OutputForm RepeatedString AppendTo ConstrainedMin EulerGamma Hypergeometri* yLog Over ow Replace Apply Construct EulerPhi Hypergeometri* LogIntegral OwnValue ReplaceAll ArcCos Context EvenQ I LogicalExpand yPSPrint ReplaceRepeat* ArcCosh ContextToFile* yExit Identity MachineID PageHeight ResetMedium ArcCot Continuation yExp IdentityMatrix MachineName PageWidth Residue ArcCoth Continue ExpIntegralE If MainSolve yParametri* Rest ArcCsc yContourGr* ExpIntegralEi Im MakeRules Part Resultant ArcCsch ContourLevels yExpand Implies Map Partition Resultant2 ArcSec yContourPlot ExpandAll In MapAll PartitionsP Return ArcSech ContourSpacing ExpandDenom* Increment MapAt PartitionsQ Reverse ArcSin Cos ExpandNumer* Indent MatchBox Pattern Right ArcSinh CosIntegral Exponent Indeterminate MatchQ PatternTest yRoots ArcTan Cosh ExponentStep Inequality MatrixExp Permutations RotateLeft ArcTanh Cot Expression yIn nity yMatrixForm yPi RotateRight Arg Coth ExtendedGCD In x MatrixPower Plain Round ArithmeticGeo* Count ExtraFactors Information MatrixQ yPlot RowReduce Array Csc ExtraTerms Inner Max yPlot3D Rule AspectRatio Csch FaceForm Input MaxBend Plot3Matrix RuleDelayed AtomQ Cubics Factor InputForm MaxIterations PlotColor RuleForm Attributes Cyclotomic FactorComplete InputString MaxMemoryUsed PlotDivision RuleTable Automatic yD FactorInteger Insert MaxRecursion PlotJoined Run Auxiliary DSolve FactorList Integer Medium PlotLabel RunThrough Axes DampingFactor FactorSquareF* IntegerQ MemberQ PlotPoints SameQ AxesEdge Dashing FactorSquareF* yIntegrate MemoryConstra* yPlotRange Save AxesLabel yDebug FactorTerms InterpolatingPo MemoryInUse PlotStyle Scaled AxesStyle yDecompose FactorTermsLi* Interrupt Mesh yPlus Scan Background Decrement Factorial Intersection MeshRange Pochhammer yScienti cFo* BaseForm Default Factorial2 yInverse MeshStyle Point Sec Begin DefaultColor Factors InverseFourier Message PointSize Sech BeginPackage DefaultValue Fail InverseFuncti* MessageName Points Second Below De nition False InverseFuncti* Messages PolyGamma SeedRandom BernoulliB Degree FindMinimum InverseJacobi* Method PolyLog Select BesselI Delimiters yFindRoot InverseJacobi* Min Polygon Sequence BesselJ Denominator First InverseJacobi* MinRecursion PolynomialG* SequenceForm BesselK DensityGraphi* Fit InverseJacobi* Minors PolynomialQ SequenceLimit BesselY DensityPlot FixedPoint InverseJacobi* Minus PolynomialQu* Series Beta Depth Flat InverseJacobi* Mod PolynomialQu* SeriesCoec* BetaRegulariz* yDerivative Flatten InverseJacobi* Mode PolynomialRe* SeriesData Binomial Det Floor InverseJacobi* yModular Position Set Blank DiagonalMatrix yFont InverseJacobi* Modulus Positive SetAccuracy BlankForm DigitBlock FontForm InverseJacobi* MoebiusMu yPostScript SetAttributes BlankNullSequ* Digits For InverseSeries Multinomial Post x SetDelayed BlankSequence Dimensions Format JacobiAmplitu* Multiplicity Power SetOptions Block DirectedIn n* FormatType JacobiCD N PowerMod SetPrecision Bottom Disk yFortranForm JacobiCN NBernoulliB PreDecrement Shading BoxRatios Dispatch Fourier JacobiCS yNIntegrate PreIncrement Share BoxStyle Display Framed JacobiDC NProduct PrecedenceFo* Sh Boxed DisplayFuncti* FreeQ JacobiDN yNRoots Precision Show Break Distribute FromASCII JacobiDS NSum Pre x Sign Byte yDivide FullDe nition JacobiNC NameQ Prepend Signature ByteCount DivideBy FullForm JacobiND Names PrependTo ySimplify C DivisorSigma Function JacobiNS Needs Prime ySin CForm Divisors GCD JacobiP Negative PrimeQ SinIntegral CallProcess Do Gamma JacobiSC Nest Print SingularValues Cancel yDot GammaRegul* JacobiSD NestList PrintForm SingularityDe* Cases DoubleExpone* GaussianQu* JacobiSN NonAssociati* PrintValue Sinh Catalan DoublyIn nite yGegenbaue* JacobiSymbol NonCommutati* ProbablePrimeQ Skeleton Catch DownValue General Jacobian NonConstants Product Slot Ceiling Drop Generic Join NonNegative Prolog SlotSequence CellArray DropFrom Get LCM None PromptForm ySolve Center Dt GoldenRatio Label Normal Protect SolveAlways Character Dump Goto LaguerreL Not Protected Sort Characters yE Gradient LaserPrint Null PseudoInverse Space ChebyshevT EdgeForm Graphics Last NullSpace Put SpaceForm ChebyshevU Edit Graphics3D LatticeReduce NumValue PutAppend SphericalHarm* Check EditDef GraphicsFont LeafCount Number Quartics Splice Chop EditIn GraphicsLeading Left NumberForm Quit ySqrt Circle Eigensystem GrayLevel LegendreP NumberPoint Quotient StartProcess Clear yEigenvalues Greater LegendreQ NumberQ RGBColor StirlingS1 ClearAll Eigenvectors GreaterEqual LegendreType NumberSepar* Random StirlingS2 ClearAttribut* ElapsedTime GroebnerBasis Length Numerator Range String Victor E. Saouma Computing Literacy for Undergraduate Engineering ClipFill yEliminate Hash LerchPhi O Rational StringBreak Close EllipticE HashTable Less OddQ Rationalize StringForm CodeAddress EllipticExp Head LessEqual O Raw StringJoin Coecient EllipticF HeadCompose Level On RawMedium StringLength
yAb
Table 12.1: Mathematica Functions
StringMatchQ StringSkeleton SubValue Subscript Subscripted Subtract
ySubtractFr* ySum
Superscript SurfaceGraphics Switch Symbol Tab Table TableForm TagSet TagSetDelayed TagUnset Take Tan T yTeXForm TensorRank Terms Text TextFont yTextForm TextLeading TextRendering Thickness Thread Through Throw Ticks TimeConstrained Times TimesBy Timing ToASCII ToExpression ToRules ToString yTogether Tolerance TooBig Top TotalHeight TotalWidth Transpose TreeForm yTrigExpand True TrueQ UnAlias Under ow Unequal Union Unique Unprotect UnsameQ Unset UpSet UpSetDelayed UpValue Update Using ValueForm ValueList ValueQ Variables Vector VerticalForm ViewPoint WeierstrassP WeierstrassP* Which While WorkingPrecis* Write WriteString WynnDegree Xor ZeroTest Zeta
Students
Draft
Chapter 13
SAMPLES of MATLAB PROGRAMS This chapter contains the description and listing of a number of simple (and not so simple) MATLAB codes. The source codes can be freely copied from /pub/Structures/cven4837
13.1 arches
13.1.1 Description
SUBDIRECTORY: arches SYNOPSIS: axial, shear, and normal force plots for an arch (Structures) DESCRIPTION: arches.m plots the Bending Moment, Shear Force, and Axial Force for a three pin semi circular arch under uniform load.
CONTENTS;
main program Written by: Brian Rose arches.m
Determine the reactions of the three-hinged arch shown in Fig. 13.1 Solution: Four unknowns, three equations of equilibrium, one equation of condition ) statically determinate. (+ ;) MzC = 0; (RAy )(140) + (80)(3:75) ; (30)(80) ; (20)(40) + RAx (26:25) = 0 ) 140RAy + 26:25RAx = 2:900 (+ - ) Fx = 0; 80 ; RAx ; RCx = 0
SAMPLES of MATLAB PROGRAMS
Draft
13{2
Figure 13.1: (+ 6) Fy = 0; (+ ;) MzB = 0;
RAy + RCy ; 30 ; 20 = 0 (Rax )(60) ; (80)(30) ; (30)(20) + (RAy )(80) = 0 ) 80RAy + 60RAx = 3; 000
(13.1-a)
Solving those four equations simultaneously we have: 2 6 6 6 4
140 26:25 0 1 1 0 80 60
0 0 1 0
0 1 0 0
38 > > 7> < 7 7 5> > > :
RAy RAx RCy RCx
9 > > > = > > > ;
8 > > > <
=> > > :
2; 900 80 50 3; 000
9 > > > = > > > ;
8 > > > <
)> > > :
RAy RAx RCy RCx
9 > > > = > > > ;
8 > > > <
=> > > :
15:1 k 29:8 k 34:9 k 50:2 k
9 > > > = > > > ;
(13.2)
We can check our results by considering the summation with respect to b from the right: (+ ;) MzB = 0; ;(20)(20) ; (50:2)(33:75) + (34:9)(60) = 0
p
(13.3)
Determine the reactions of the three hinged statically determined semi-circular arch under its own dead weight w (per unit arc length s, where ds = rd). 13.2
Figure 13.2: Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.1 arches
13{3
The reactions can be determined by integrating the load over the entire structure (+ ;) MA = 0;
;(VC )(2R) +
Z
=
(1 +{zcos }) = 0 wRd} R |
{z =0 | dP Z =
moment arm ) VC = wR 2 =0 (1 + cos )d = wR = wR 2 [ ; sin ] j=0 = 2 [( ; sin ) ; (0 ; sin 0)] = 2 wR Next we determine the horizontal reaction Z = 2 (+ ) MB = 0; ;(HC )(R) + (Vc )(R) ; wRd R cos =0 | {z } | {z } ;
wR ; wR
) HC
Z
= 2
dP moment arm
(13.4-a)
=0
2 =0 cos d = 2 = wR ; wR( ; 0) = 2 wR ; wR[sin ] j=0 2 ; 2 = 2 ; 1 wR
=2
(13.5-a)
By symmetry the reactions at A are equal to those at C Draw the shear and moment diagram for the three hinged statically determined semi-circular arch under its own dead weight w, Fig. 13.3. Solution:
Reactions: Those were determined earlier, Example ??. For the sake of clarity, we repeat their derivation: 1. Starting with CY
(+ ;) MA = 0;
;(CY )(2R) +
Z
=
wRd} R (1 +{zcos }) = 0 |
{z =0 | dP Z =
moment arm ) CY = wR 2 =0 (1 + cos )d = wR = wR 2 [ ; sin ] j=0 = 2 [( ; sin ) ; (0 ; sin 0)] (13.6-a) = 2 wR 2. Next we determine the horizontal reaction Z = 2 (+ ) MB = 0; ;(Cx )(R) + (Cy )(R) ; wRd R cos =0 | {z } | {z } ;
) Cx
= 2 wR ; wR 2
=
= 2
=0
cos d
=0 wR ; wR(sin ] j= 2 = wR ; wR( =0 2 2 2 ; = ; 1 wR
2
Victor E. Saouma
Z
dP moment arm
; 0)
(13.7-a)
Computing Literacy for Undergraduate Engineering Students
SAMPLES of MATLAB PROGRAMS
Draft
13{4
Figure 13.3:
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.1 arches
13{5
3. By symmetry the reactions at A are equal to those at C Shear Forces: Considering the free body diagram of the arch, and summing the forces in the radial direction (FR = 0): Z ;( 2 ; 1)wR cos + 2 wR sin ; wRd sin + V = 0 |
{z
Cx
}
(13.8)
=0
| {z }
Cy
) V = wR ( 2 ; 1) cos + ( ; 2 ) sin
(13.9)
Axial Forces: Similarly, if we consider the summation of forces in the axial direction (FN = 0):
(
; 1)wR sin + wR cos ;
Z
wRd cos + N = 0 2 ; 1) sin
(13.10) (13.11)
Moment: Now we can consider the third equation of equilibrium (M = 0): ( 2 ; 1)wR R sin ; 2 wR2 (1 ; cos ) + Z wRd R(cos ; cos ) + M = 0 =0 M = wR2 2 (1 ; sin ) + ( ; 2 ) cos
(13.12) (13.13)
2
N = wR
2
=0 ( ; ) cos ; (
2
We seek to determine the vertical de ection of the crown of the three hinged statically determined semi-circular arch, Fig. 13.4 under its own dead weight w, Fig. ??. 1. We rst seek to determine the analytical expression of the moment diagram. From statics, it can be shown that the vertical and horizontal reactions are Rv = 2 wR and Rh = ( 2 ; 1)wR. 2. Next considering the free body diagram of the arch, and summing the forces in the radial direction (FR = 0): Z
wRd sin + V = 0 ;( 2 ; 1)wR cos + 2 wR sin ; =0 V = wR ( 2 ; 1) cos + ( ; 2 ) sin
(13.14-a) (13.14-b)
3. Similarly, if we consider the summation of forces in the axial direction (FT = 0): Z
( 2 ; 1)wR sin + 2 wR cos ; wRd cos + N = 0 =0 N = wR ( ; 2 ) cos ; ( 2 ; 1) sin Victor E. Saouma
(13.15-a) (13.15-b)
Computing Literacy for Undergraduate Engineering Students
SAMPLES of MATLAB PROGRAMS
Draft
13{6
Figure 13.4:
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.1 arches
13{7
4. Now we can consider the third equation of equilibrium (M = 0): ( 2 ; 1)wR R sin ; 2 wR2 (1 ; cos ) + Z
wRd R(cos ; cos ) + M = 0 M = wR2 2 (1 ; sin ) + ( ; 2 ) cos
(13.16-a) (13.16-b)
=0
5. The real curvature is obtained by dividing the moment by EI 2 M wR = EI EI 2 (1 ; sin ) + ( ; 2 ) cos
(13.17)
6. The virtual force P will be a unit vertical point in the direction of the desired de ection, causing a virtual internal moment
M = R2 [1 ; cos ; sin ]
0 2
(13.18)
7. Hence, application of the virtual work equation yields: 2 wR 1 = 2 (1 ; sin ) + ( ; 2 ) cos R2 [1 ; cos ; sin ] Rd |{z} |{z} EI 2 =0 | {z } dx {z } | Z
2
P
wR4
h
= 16EI 72 ; 18 ; 12 4 = :0337 wR EI
i
M
(13.19-a)
13.1.2 Listing 13.1.2.1
arches.m
Equations used for calculation of shear force, axial force, and bending moment are as follows:
V = !R[( 2 ; 1) cos + ( ; 2 ) sin ] N = !R[( ; 2 ) cos ; ( 2 ; 1) sin ] M = !R2 [ 2 (1 ; sin ) + ( ; 2 ) cos ] arches.m le starts here: Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
SAMPLES of MATLAB PROGRAMS
Draft
13{8
Figure 13.5: Simply Supported Arch with Uniform Load %Arches is a script that plots the Bending Moment, Shear Force, %and Axial Force for a three pin semi circular arch under uniform %load %clear the command screen clc %prompt the user for some information R=input('Enter the radius of the arch: '); w=input('Enter the load on the of the arch: '); %create a vector of theta from 0 to 90 degrees theta=(0:pi/100:pi/2); %calculate V, N, M for a half the arch V=w*R*((pi/2-1)*cos(theta)+(theta-pi/2).*sin(theta)); N=w*R*((theta-pi/2).*cos(theta)-(pi/2-1)*sin(theta)); M=w*R^2*(pi/2*(1-sin(theta))+(theta-pi/2).*cos(theta)); %since the structure is symmetric, get V,N,M values %for theta from 90 to 180 degrees by flipping V,N,M %notice the negative sign for Shear %also note that if we just flip V,N,M we'll %repeat V(90 degrees),N(90 degrees), M(90 degrees) %so we'll pull those values out V=[V fliplr(-V(1:length(V)-1))]; N=[N fliplr(N(1:length(N)-1))]; M=[M fliplr(M(1:length(M)-1))]; %redefine theta so that it goes from 0 to 180 degrees theta=(0:pi/100:pi);
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.2 beam1
13{9
%Plot the shear diagram %The axislimit=... commands are there so that I can %tell Matlab to do a polar plot with a radial axis starting from %-V to +V, instead of 0 to +V. %The tickmarks=... command makes it so that the tick labels are nice round numbers %Also note that we are not using the command polar, but instead we're using %polarhg. Polarhg is a more flexible version of polar, but it doesn't come %standard with Matlab subplot(221) axislimits=max(abs(V))*1.2; axislimits=ceil(axislimits/10.^floor(log10(axislimits)))*10.^floor(log10(axislimits))*[-1 1]; tickmarks=(axislimits(1):2*10^floor(log10(axislimits(2))):axislimits(2)); polarhg([theta;theta],[V;0*V],'rlim',axislimits,'rtick',tickmarks); title('Shear Force') %plot the Axial force diagram subplot(222) axislimits=max(abs(N)); axislimits=ceil(axislimits/10.^floor(log10(axislimits)))*10.^floor(log10(axislimits))*[-1,1]; tickmarks=(axislimits(1):2*10^floor(log10(axislimits(2))):axislimits(2)); polarhg([theta;theta],[N;0*N],'rlim',axislimits,'rtick',tickmarks); title('Axial Force') %plot the Moment diagram subplot(223) axislimits=max(abs(M)); axislimits=ceil(axislimits/10.^floor(log10(axislimits)))*10.^floor(log10(axislimits))*[-1,1]; tickmarks=(axislimits(1):2*10^floor(log10(axislimits(2))):axislimits(2)); polarhg([theta;theta],[-M;0*M],'rlim',axislimits,'rtick',tickmarks); title('Bending Moment')
13.2 beam1
13.2.1 Description
SUBDIRECTORY : beam1 SYNOPSIS: shear and bending moment diagram for a simple beam (Structures) DESCRIPTION: BMdemo.m gets the bending moment and de ection for a simply supported beam subjected to either a point load or a distributed load.
CONTENTS:
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
SAMPLES of MATLAB PROGRAMS
Draft
13{10 Shear Force 200 90 60 120 0
150
30
−200
180
0
210
330 240
270
300
Axial Force 400 90 60 120 200 0 150 −200 −400 180 210
30 0 330
240
270
300
Bending Moment 3000 90 120 60 1000 150
−1000 −3000
180 210
30 0 330
240
270
300
Figure 13.6: Sample output for arches.m using r = 100 and != 2 BMdemo.m M2deflection.m P2M.m P2V.m w2M.m w2V.m
Written by: Brian Rose
the main program converts bending moments to de ections by integration converts point loads to moment using a formula converts point loads to shear using a formula converts uniform loads to moment using a formula converts uniform loads to shear using a formula
13.2.2 Listing 13.2.2.1
BMdemo.m
Equations used for calculation of shear, bending moment, and de ection diagrams:
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
13{11
Draft
13.2 beam1
Figure 13.7: Simply Supported Beams with Various Loadings
Pointload
R1 = Pb L
R2 = Pa L
M = R1 x
for (x < a) for (x a)
= R2 (L - x)
V = R1
for (x < a)
= ;R2 ;
for (x a)
v00 = MEI(i) = v(i ; 1) ; 2dxv(2i) + (i + 1)
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{12
SAMPLES of MATLAB PROGRAMS Continuous Load
R1 = 2!bL (2a + b)
R2 = 2!bL (2c + b) M = R1 x
for (x < a)
= R1 x ; !2 (x ; a)
for (a x a + b) for (x a + b)
= R2 (L - x)
V = R1
for (x < a)
= (x ; a)(;bR2 ; R1 ) + R1
= ;R2
for (a x a + b) for (x a + b)
v00 = MEI(i) = v(i ; 1) ; 2dxv(2i) + (i + 1) BMdemo.m le starts here: %BMdemo %this script gets the bending moment and %deflection for a simply supported beam subjected to either %a point load or a distributed load %prompt the user for the load type choice=input('Analyze for point load (1) or a uniform load (2) ? '); %clear the screen clc %do the point load case if choice==1 %prompt the user for some parameters P=input('Enter P: '); a=input('Enter a: '); L=input('Enter L: '); E=input('Enter E: '); I=input('Enter I: '); number_points=input('Enter the number of discretization points: '); %calculate the mesh size
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.2 beam1
13{13
dx=L/(number_points-1); %get the BM M=P2M(P,a,L,dx); %get the shear V=P2V(P,a,L,dx); %get the deflection v=M2deflection(M,E,I,dx); %do the distributed load case elseif choice==2 %prompt the user for some parameters w=input('Enter w: '); a=input('Enter a: '); b=input('Enter b: '); L=input('Enter L: '); E=input('Enter E: '); I=input('Enter I: '); number_points=input('Enter the number of discretization points: '); %calculate the mesh size dx=L/(number_points-1); %get the deflection M=w2M(w,a,b,L,dx); %get the Shear V=w2V(w,a,b,L,dx); %get the deflection v=M2deflection(M,E,I,dx); end %plot the BM and deflection %make a vector for location along beam x=(0:dx:L); %plot the BM subplot(311) plot(x,M) ylabel('Bending Moment') grid %plot the Shear subplot (312) plot(x,V) ylabel('Shear') grid
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
SAMPLES of MATLAB PROGRAMS
%plot the deflection subplot(313) plot(x,v) ylabel('Displacement') grid
Shear
Bending Moment
4
6
x 10
4 2 0 0 4 x 10 1
2
4
6
8
10
12
2
4
6
8
10
12
2
4
6
8
10
12
0
−1 0 0
Displacement
Draft
13{14
−0.5 0
Figure 13.8: Sample output of BMdemo.m with a pointload using P = 20 kN, a = 6 m, L = 12 m, E = 200 GPa, I = 6e6 mm4 , and 12 discretization points.
13.2.2.2
M2deflection.m
function v=M2deflection(M,E,I,dx) %M2DEFLECTION(M,E,I,dx) returns the deflection of a simply %supported beam, given the descritized moment, M; %E, Young's modulus; I, moment of inertia; and dx, %the mesh size. % %This algorithm integrates the bending moment twice %using the central difference method. %The second derivative is defined as %
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.2 beam1
13{15
% v(i-1) - 2v(i) + (i+1) %v''= ---------------------% dx^2 % % %Using the central difference method we can w%The central difference method will take on the form Av=b.rite % % v(i-1) - 2v(i) + (i+1) %M(i)/EI = ---------------------% dx^2 % %If you write the above equation for every mesh point %you get the following matrix equation. % % -------% | 1 -2 1 | | v(-1) | | M(0) | % | 1 -2 1 | | v(0) | | M(1) | % | 1 -2 1 | | v(1) | | M(2) | % | . | | v(2) | | . | %1/dx^2 | . | | . | = 1/EI | . | % | . | | . | | . | % | 1 -2 1 | | . | | M(n) | % | 1 | | v(n) | | 0 | % | 1 | | v(n+1)| | 0 | % -------% % |________________________________| |_______| |______| % A v b % %v(-1) and v(n+1) are known as the phantom points,and %they do not represent any real displacements. The last two %lines embody the boundary conditions: v(0)=0 and v(n)=0. By %solving for v in the matrix equation Av=b, you will obtain %the displacements, including the phantom points. %get the number of discretization points m=length(M); %make a diagonals for the matrix firstdiagonal=ones(m+2,1)/dx^2; seconddiagonal=-2*ones(m+1,1)/dx^2; thirddiagonal=ones(m,1)/dx^2; %make a tridiagonal matrix of dimensions (m+2,m+2) A=diag(firstdiagonal,0)+diag(seconddiagonal,1)+diag(thirddiagonal,2); %replace the last row with a bunch of zeros A(m+1:m+2,:)=zeros(2,m+2); %now put ones in the appropriate places A(m+1,2)=1; A(m+2,m+1)=1;
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{16
SAMPLES of MATLAB PROGRAMS
%make the vector b b=M/(E*I); b(m+1)=0; b(m+2)=0; %make sure that b is a column vector if size(b,1)==1 b=b'; end %solve the system of equations v=(A\b); %discard the phantom points v=v(2:m+1);
13.2.2.3
P2M.m
function M=P2M(P,a,L,dx) %FUNCTION M=P2M(P,A,L,dx) returns the bending moment diagram for a %point load on a simply supported beam % % |P % | % \|/ % __________________________ % /\ /\ % |----A----| % |------------L------------| % %
|-------B-------| |---> x
%get b b=L-a; %get the reactions R1=P*b/L; R2=P*a/L; %make a vector x x=(0:dx:L); %get the moment M=R1*(x=a).*(L-x); %the above statement is a shorthand way of saying %for i=1:length(x) % if x(i) < a
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.2 beam1
13{17
% M(i)=R1*x(i); % elseif x(i) >= a % M(i)=R2*(L-x(i)); % end %end %Matlab is very fast at evaluating matrix operations %like the shorthand command for M. Matlab is not so fast %at doing if statements and for loops.
13.2.2.4
P2V.m
function V=P2V(P,a,L,dx) %FUNCTION V=P2V(P,A,L,dx) returns the Shear diagram for a %point load on a simply supported beam % % |P % | % \|/ % __________________________ % /\ /\ % |----A----| % |------------L------------| % %
|-------B-------| |---> x
%get b b=L-a; %get the reactions R1=P*b/L; R2=P*a/L; %make a vector x x=(0:dx:L); %get the shear V=(x=a)*R2; %the above statement is a shorthand way of saying %for i=1:length(x) % if x(i) < a % V(i)=R1; % elseif x(i) >= a % V(i)=-R2; % end %end %Matlab is very fast at evaluating matrix operations
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{18
SAMPLES of MATLAB PROGRAMS
%like the shorthand command for M. Matlab is not so fast %at doing if statements and for loops.
13.2.2.5
w2M.m
function M=w2M(w,a,b,L,dx) %FUNCTION M=w2M(W,a,b,L,dx) returns the bending moment diagram for a %distributed load on a simply supported beam % % % _______ % ||||||| w % __________________________ % /\ /\ % |--A--|--B--| % |------------L------------| % %
|---> x |--------C----|
%get c c=L-a-b; %get the reactions R1=w*b/2/L*(2*c+b); R2=w*b/2/L*(2*a+b); %make a vector x x=(0:dx:L); %get the bending moment M=(x=a)&(x<(a+b))).*(R1*x-w/2*(x-a).^2) + (x>=(a+b)).*(R2*(L-x)); %the above statement is a shorthand way of saying %for i=1:length(x) % if x(i) < a % M(i)=(x(i)*R1); % elseif (x(i) >= a) &| (x(i) < (a+b)) % M(i)=(R1*x(i)-w/2*(x(i)-a).^2); % elseif (x(i) >= (a+b)) % M(i)=(R2*(L-x(i))); % end %end %Matlab is very fast at evaluating matrix operations %like the shorthand command for M. Matlab is not so fast %at doing if statements and for loops.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.2 beam1 13.2.2.6
13{19
w2V.m
function V=w2V(w,a,b,L,dx) %FUNCTION V=w2V(W,a,b,L,dx) returns the shear diagram for a %distributed load on a simply supported beam % % % _______ % ||||||| w % __________________________ % /\ /\ % |--A--|--B--| % |------------L------------| % %
|---> x |--------C----|
%get c c=L-a-b; %get the reactions R1=w*b/2/L*(2*c+b); R2=w*b/2/L*(2*a+b); %make a vector x x=(0:dx:L); %get the shear V=(x=a)&(x<(a+b))).*((x-a)*(-R2-R1)/b+R1) - (x>=(a+b))*R2; %the above statement is a shorthand way of saying %for i=1:length(x) % if x(i) < a % V(i)=R1 % elseif (x(i) >= a) & (x(i) < (a+b)) % V(i)=(x-a)*(-R2-R1)/b+R1 % elseif (x(i) >= (a+b)) % V(i)=-R2 % end %end %Matlab is very fast at evaluating matrix operations %like the shorthand command for M. Matlab is not so fast %at doing if statements and for loops.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{20
SAMPLES of MATLAB PROGRAMS
13.3 beam2
13.3.1 Description
SUBDIRECTORY: beam2 SYNOPSIS: principle stress plots in a simple beam under midspan point load (Structures) DESCRIPTION: beam under load.m plots the principle stresses in a prismatic rectangular beam under uniform loads, with simple supports, assuming plane stress conditions.
CONTENTS:
beam under load.m
main program
Written by: Brian Rose
13.3.2 Listing 13.3.2.1
beam under load.m
Figure 13.9: Beam Under Continuous Load Major formulas used:
M = !2 x(L ; x) V = !9 L2 ; x) Q = b( d ; y)( y + d ) 2
Victor E. Saouma
2
4
Computing Literacy for Undergraduate Engineering Students
13.3 beam2
13{21
Draft
xx = ; My I V Q = Ib
s
2 1;2 = 2xx 4xx + 2
beam under load.m le starts here: %script beam_under_load will plot the principle stresses in a prismatic %rectangular beam under uniform loads, with simple supports. We will %assume plane stress conditions. %beam is depth d, width b, length L and has uniform load of w %define dimensions b=4; d=12; L=20*12; %define the uniform load w=2; %get some cross sectional properties A=b*d; I=b*d^3/12; %set up x and y coordinate system numberx=100; numbery=40; x=0:L/numberx:L; y=-d/2:d/numbery:d/2; %get a mesh of x and y's [x,y]=meshgrid(x,y); %calculate moment and shear M=w/2*x.*(L-x); V=w*L/2-w*x; %calculate the first moment of intertia Q=b*(d/2-y).*(y/2+d/4); %calculate bending stress and shear stress for each point in the beam sb=-M.*y/I; sv=V.*Q/I/b; %calculate the principle and maximum shear stresses tmax=sqrt(sb.^2/4+sv.^2); p1=sb/2+tmax; p2=sb/2-tmax;
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{22
SAMPLES of MATLAB PROGRAMS
%set the colorscale for the plots %for more details type "help color" and "help colormap" colormap(jet) %plot results %the shading interp takes away ugly gridlines subplot(311) pcolor(x,y,p1) shading interp title('Principle Stress 1') colorbar subplot(312) pcolor(x,y,p2) shading interp title('Principle Stress 2') colorbar subplot(313) pcolor(x,y,tmax) shading interp title('Maximum Shear Stress') colorbar %for those of you who appreciate psychedelic stuff try this %spinmap(20)
13.4 boussinesq 13.4.1 Description
SUBDIRECTORY: boussinesq SYNOPSIS: stress plot for semi-in nite domain under a point load (Geotech) DESCRIPTION: boussinesq.m plots the stress distribution of a point load on a semi-in nite half space
CONTENTS:
main program Written by: Brian Rose boussinesq.m
13.4.2 Listing 13.4.2.1
boussinesq.m
Main formula: Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.4 boussinesq
13{23 Principle Stress 1 150
5
100 0 50 −5 0
50
100 150 Principle Stress 2
0
200
0
5
−50 0 −100 −5 0
50
100 150 Maximum Shear Stress
−150
200
5 60 40
0
20 −5 0
50
100
150
Figure 13.10: Sample output of with ! = 2; b = 4; d = 12; and L = 20.
0
200
principle stresses
for
beam under load.m
)3 y = 3P2(sin R2 boussinesq.m le starts here: %script boussinesq plots the stress distribution %of a point load on a semi-infinite half space % % % | P % | % | % \|/ %-----------------------------% % --->x % | % | % |/ y %set up a radial grid %define the r's and theta's for our grid as vectors r=0.01:.002:0.1; theta=0:pi/20:pi; P=100;
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
SAMPLES of MATLAB PROGRAMS
Draft
13{24
Figure 13.11: Point Load on Semi-In nite Domain
%Now define a R and THETA for each grid point %this means that R and THETA are both matrices [R,THETA]=meshgrid(r,theta); %get the stress in the y direction stressy=3*P/(2*pi)*(sin(THETA)).^3./R.^2; %take R and THETA and convert them to cartesian coordinates [x,y] = pol2cart(THETA,R); %plot the results (note the -y is so that %it plots upside down pcolor(x,-y,stressy)
%note that since the solution blows up at R=0 and theta=0, %we have left out the solution for that point.
13.5 dodgecity
13.5.1 Description
SUBDIRECTORY: dodgecity SYNOPSIS: statistical analysis of wind power in Dodge City (Energy Management) DESCRIPTION: wind.m makes a histogram of windspeed and does some simple statistics on it. Accompanies Jan Kreider's handout "Wind Power Assessment"
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
13.5 dodgecity
13{25
Draft
0 −0.01 −0.02 −0.03 −0.04 −0.05 −0.06 −0.07 −0.08 −0.09 −0.1 −0.1
−0.08
−0.06
−0.04
−0.02
0
0.02
0.04
0.06
0.08
0.1
Figure 13.12: Stress plot for point Load on Semi-In nite Domain
CONTENTS:
data le data le data le data le data le data le data le data le data le data le data le data le main program Written by: Brian Rose apr aug dec feb jan jul jun mar may nov oct sep wind.m
13.5.2 Listing 13.5.2.1
wind.m
Equation used:
P = 12 v3 wind.m le starts here: Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{26
SAMPLES of MATLAB PROGRAMS
%Script wind.m %Makes a histogram of windspeed and does some simple statistics` %on it. Accompanies Jan Kreider's handout Wind Power Assessment %load data for all 12 months %use the -ascii extension to tell Matlab that we're reading ascii %files. Matlab will take the data in the file jan and stuff it into %a matrix called jan. Same goes for all the other months load load load load load load load load load load load load
jan feb mar apr may jun jul aug sep oct nov dec
-ascii -ascii -ascii -ascii -ascii -ascii -ascii -ascii -ascii -ascii -ascii -ascii
%Concatentate them into one big matrix called data data=[jan;feb;mar;apr;may;jun;jul;aug;sep;oct;nov;dec]; %now pull out the wind speed from the 7th column of data V=data(:,7); %specify the bins %the bin goes from 0 to the maximum windspeed rounded up to the %next whole number. Try typing 'help ceil' in the matlab window bin=(0:ceil(max(V))); %sort the velocity into bins hours=hist(V,bin); %make a histogram %on your own try doing bar(bin,hours) and bar(midpoint,hours). %the results will be slightly different. midpoint=bin+0.5; bar(midpoint,hours) title('Dodge City') xlabel('Wind Velocity (m/s)') ylabel('Hours') %Compute power. %Note here that the we use .^3 instead of ^3 %because the former is an array operation (means operate %element by element), whereas the latter is a matrix operation. rho=1.124; Power=rho/2*(V.^3);
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
13{27
%do some statistics on power mean_power=mean(Power) max_power=max(Power) std_power=std(Power) median_power=median(Power)
Dodge City 1400
1200
1000
800
Hours
Draft
13.6 eectiveL
600
400
200
0 0
5
10
15 Wind Velocity (m/s)
20
25
30
Figure 13.13: Sample histogram of windspeed Simple Statistics calculated from wind data: mean_power =
194.0820
max_power =
8.7812e+03
std_power =
311.3429
median_power =
70.2500
13.6 eectiveL
13.6.1 Description
SUBDIRECTORY: eectiveL Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{28
SAMPLES of MATLAB PROGRAMS
SYNOPSIS: eective length of a sidesway inhibited column of a building (Structures) DESCRIPTION: eectiveL.m returns the eective length factor, K given the G values for the top and bottom of a sidesway inhibited column.
CONTENTS:
effectiveL.m
main function. Note, not a scipt.
Recall that the Euler buckling load was derived for a pinned column. In many cases, a column will have dierent boundary conditions. It can be shown that in all cases, the buckling load would be given by
2 Pcr = EI2 (KL) where K is called eective length factor, and KL is the eective length. and 2 cr = E2 KL
(13.20)
(13.21)
r
The ratio KL r is termed the slenderness ratio. The eective length, can only be determined by numerical or approximate methods, and is the distance between two adjacent (real or virtual) in ection points, Fig. 13.14, 13.15 P
P P
P
KL = 0.7L KL = L
L
KL =
1 L L 2
KL < L
L
P P
P
P (a) End rotations unrestrained
(b) End rotations fully restrained
(c) One end restrained, other unrestrained
(d) Partially restrained at each end
Figure 13.14: Column Eective Lengths Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
13.6 eectiveL
Draft
13{29
∆ P
P
P
P
KL 2 L
L 0.7L
KL>2L
∆
(a) Braced frame, hinged base P
P
L
0.5L
(b) Unbraced frame, hinged base P
P
L L
(c) Braced frame, fixed base
(d) Unbraced frame, fixed base
Figure 13.15: Frame Eective Lengths The most widely used charts for the eective length determination are those produced by the Structural Stability Research Council. The alignment chart, for an individual column, Fig. 13.16 is shown in Fig. 13.17. It should be noted that this chart assumes that all members are still in the elastic range. The use of the alignment chart involces computing G at each end of the column using the following formula P Ic
Ga = P LIgc Lg
(13.22)
where Ga is the stiness at end a of the column, Ic, Ig are the moment of inertias of the columns and girders respectively. The summation must include only those members which are rigidly connected to that joint and lying in the plane for which buckling is being considered. Hence, once Ga and Gb are determined, those values are connected by a straight line in the appropriate chart, and k is the point of intersection of that line with the midle axis. Alternatively :-)
GAGB 2 + GA + GB 1 ; =K + 2 tan =2K = 1 4 K 2 tan =K =K
(13.23)
(Ref. McGuire P. 467). Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
SAMPLES of MATLAB PROGRAMS
Draft
13{30
Figure 13.16: Column Eective Length in a Frame
13.6.2 Listing 13.6.2.1
effectiveL.m
function K=effectiveL(Ga,Gb) %K=effectiveL (Gtop, Gbot) returns the effective length %factor, K given the G values for the top and bottom of a %sidesway inhibited column. % %K can be found by solving the following equation numerically % % _ _ _ _ 2 _ _ _ _ %| Ga Gb | | pi | | Ga+Gb | | pi/K | 2 tan(pi/2K) %| ----- | | ---- | + |-------- | | 1 - --------- | + ------------- = 1 %| 4 | | K | | 2 | | tan(pi/K) | pi/K % % %This function uses a root finding scheme, namely the bisection %method to find the root of the following equation. % % _ _ _ _ 2 _ _ _ _ % | Ga Gb | | pi | | Ga+Gb | | pi/K | 2 tan(pi/2K) %R = | ----- | | ---- | + |-------- | | 1 - --------- | + ------------- - 1 % | 4 | | K | | 2 | | tan(pi/K) | pi/K % %
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
13{31
Draft
13.6 eectiveL
Sidesway Inhibited 150.
Ga
10. 5. 3. 2. 1. 0.8 0.7 0.6 0.5 0.4 0.3 0.2
K 1.0 0.9 0.8 0.7
0.6
0.1 0.
Sidesway Uninhibited Gb
1 50.
10. 5. 3. 2. 1. 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1
0.5
0.
1
Ga
K
100. 50. 30. 20. 10. 9. 8. 7. 6. 5. 4. 3. 2.
1 20. 10. 5. 4. 3.
2.
1.5
1. 0
Gb
1
100. 50. 30. 20. 10. 9. 8. 7. 6. 5. 4. 3. 2. 1.
1.
0
Figure 13.17: Standard Alignment Chart (AISC)
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{32
SAMPLES of MATLAB PROGRAMS
% note: R is the residual and we want to find K such that R=0; % %For this method, we make two guesses of K, Klower and Kupper, that %bound the correct K. Then, we estimate K as the average of the %two initial guesses. Next we figure out if our if the estimated %K and Kupper or the estimated K and Klower bound the solution. %Then with the two new bounds, we start over again. % %More ambitious people can use the Matlab function fzero
%define upper and lower bounding estimates of K Kupper=.98; Klower=.52; %define the tolerance for rootfinding tolerance=1e-3; %get the residual for the upper and lower bounding estimates Rupper=Ga*Gb/4*(pi/Kupper)^2 + (Ga+Gb)/2*(1-pi/Kupper/tan(pi/Kupper))+2*tan(pi/2/Kupper)/(pi/Kupper)-1; Rlower=Ga*Gb/4*(pi/Klower)^2 + (Ga+Gb)/2*(1-pi/Klower/tan(pi/Klower))+2*tan(pi/2/Klower)/(pi/Klower)-1; %set R to something big so that we can enter the loop R=100*tolerance; %loop until we find the root while abs(R)>tolerance %let our estimate of K be halfway between Kupper and Klower K=(Kupper+Klower)/2; %calculate the residual corresponding to K R=Ga*Gb/4*(pi/K)^2 + (Ga+Gb)/2*(1-pi/K/tan(pi/K))+2*tan(pi/2/K)/(pi/K)-1; %if K and Kupper bound the root let Klower=K if R>0 Klower=K; Rlower=R; %if K and Klower bound the root let Kupper=K else Kupper=K; Rupper=R; end end
13.7 eigenvalues 13.7.1 Description
SUBDIRECTORY: eigenvalues Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.7 eigenvalues
13{33
SYNOPSIS: Principle stresses and directions of a 3-Dimensional stress element DESCRIPTION: eigenvalues.m prompts the user for stress components of a 3-dimensional stress element and then calculates the principal stresses and directions.
CONTENTS:
main program Written by: Brian Rose eigenvalues.m
13.7.2 Listing 13.7.2.1
eigenvalues.m
Figure 13.18: 3-Dimensional Stress Element %The script "eigenanalysis" prompts the user for stress components %in 3-D. Then is calculates the principle stresses and the %principle directions %clear the screen
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{34
SAMPLES of MATLAB PROGRAMS
clc %prompt user for some numbers %note that I can define the elements of the matrix %without even defining the size of the matrix before hand Stress(1,1)=input('Enter normal stress on x face: '); Stress(2,2)=input('Enter normal stress on y face: '); Stress(3,3)=input('Enter normal stress on z face: '); Stress(1,2)=input('Enter shear stress xy: '); Stress(1,3)=input('Enter shear stress xz: '); Stress(2,3)=input('Enter shear stress yz: '); %Make the stress matrix symmetric %First pull out the upper triangular part of the matrix (without the diagonal). %Second transpose the part we pulled out and add it to the Stress matrix %for more details on the command triu, try typing "help triu" Stress temp=triu(Stress,1) Stress=Stress+temp' %Now do the eigenanalysis [eigenvectors,principle_stress]=eig(Stress); %Display the results as well as the stress matrix %clc disp('The stress tensor is') disp(Stress) disp(' ') disp(' ') for i=1:3 disp('Principle stress number') disp(i) disp(principle_stress(i,i)) disp('Its unit normal is:') disp(eigenvectors(:,1)') disp(' ') disp(' ') end Sample run: >> eigenvalues Enter normal stress on x face: 3 Enter normal stress on y face: 4 Enter normal stress on z face: 1 Enter shear stress xy:
2
Enter shear stress xz:
5
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.7 eigenvalues
13{35
Enter shear stress yz:
8
Stress = 3 0 0
2 4 0
5 8 1
2 0 0
5 8 0
2 4 8
5 8 1
temp = 0 0 0
Stress = 3 2 5 The stress 3 2 5
tensor is 2 5 4 8 8 1
Principle stress number 1 1.4822 Its unit normal is: -0.8460 0.5314
0.0442
Principle stress number 2 -6.4509 Its unit normal is: -0.8460 0.5314
0.0442
Principle stress number 3
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{36
SAMPLES of MATLAB PROGRAMS
12.9688 Its unit normal is: -0.8460 0.5314
0.0442
13.8 in ltration 13.8.1 Desctiption
SUBDIRECTORY: in ltration SYNOPSIS: in ltration of water in soil where ponding has occured (Hydrology) DESCRIPTION: in ltration.m calculates the the depth of in ltration of water in a soil medium after ponding has occured. The problem is taken from "Applied Hydrology" by V.Chow, D. Maidment, and L. Mays page 120, example 4.4.2.
CONTENTS:
infiltration.m
main program
Written by: Brian Rose
13.8.2 Listing
13.8.2.1 in ltration.m Equation used:
F = Fp + ln[ ++ FF ] + k(t ; tp ) p in ltration.m le starts here: %script infiltration will calculate the the depth of infiltration %of water in a soil medium after ponding has occured. The problem is %taken from "Applied Hydrology" by V.Chow, D. Maidment, and L. Mays %page 120, example 4.4.2. % %The equations is % % psiDtheta + F % F - Fp - (psiDtheta)*ln ---------------- = K (t-tp). % psiDtheta + Fp % % %We will solve this equation for F by rewriting the above as % % psiDtheta + F
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.9 montecarlo
13{37
% F = Fp + (psiDtheta)*ln ---------------- + K (t-tp). % psiDtheta + Fp % %First we will guess an F. Then we will plug this F into the right hand %side of the equation. This will give us a new F. We will then %plug this new F into the right hand side and so on. %define the contants Fp=0.85 psiDtheta=5.68 K=0.65 tp=.17 t=1 %make an initial guess of F F=.2; %iterate for i=1:1000 F=Fp+psiDtheta*log((psiDtheta+F)/(psiDtheta+Fp))+K*(t-tp); end %display F F Sample run: >> infiltration Fp =
0.8500
psiDtheta = K =
5.6800
0.6500
tp =
0.1700
t =
1
F =
3.0176
13.9 montecarlo 13.9.1 Description
SUBDIRECTORY: montecarlo SYNOPSIS: montecarlo simulation of a simple beam under midspan point load (Structures and Statistics)
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{38
SAMPLES of MATLAB PROGRAMS
DESCRIPTION: montecarlo.m does a monte carlo simulation for a simply supported beam
under a point load at the midspan. The load, P and the yield stress, fy are normally distributed.
CONTENTS:
main program Written by: Brian Rose montecarlo.m
13.9.2 Listing 13.9.2.1
montecarlo.m
%script montecarlo does a monte carlo simulation for a simply %supported beam under a point load at the midspan %the load, P and the yield stress, fy are normally distributed %define a sample size samplesize=5000; %define the properties of the beam L=480; S=150; %define the mean and standard deviation for %yield stress and load meanfy=36 meanP=40 stdfy=1 stdP=1 %get a normally distributed set of stress values and %a normally distributed set of load values %note that randn gives me a standard normal %distribution so I have to convert to a normal %distribution fy=meanfy+stdfy^2*randn(samplesize,1); P=meanP+stdP^2*randn(samplesize,1); %calculate the max stress in a simple span beam loaded in the center M=P*L/4; f=M/S; %define X=capacity/demand X=fy./f; %plot f and fy subplot(211) bin=(30:.1:42); plot(bin,hist(f,bin)/samplesize,bin,hist(fy,bin)/samplesize) legend('computed stress','yield stress');
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
13{39
xlabel ('stress (ksi)') ylabel('PDF') grid %plot X subplot(212) bin=(-0.5:0.1:2); plot(bin,hist(log(X),bin)/samplesize); legend('computed stress','yield stress'); xlabel ('ln of C/D (ksi)') ylabel('PDF of ln(C/D)') legend off grid
%get the safety index %note that log denotes the natural log beta=mean(log(X))/std(log(X)) %get the probability of failure failureP=sum(f>fy)/length(f)
0.06 0.05 computed stress yield stress
PDF
0.04 0.03 0.02 0.01 0 30
32
34
36 stress (ksi)
38
40
42
0.8
PDF of ln(C/D)
Draft
13.9 montecarlo
0.6 0.4 0.2 0 −0.5
0
0.5 1 ln of C/D (ksi)
1.5
2
Figure 13.19: Sample output for a monte carlo simulation for a simply supported beam under a point load at the midspan.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{40
SAMPLES of MATLAB PROGRAMS
13.10 3dplot
13.10.1 Description
SUBDIRECTORY : 3Dplots SYNOPSIS: takes elevation readings and plots them in 3D (Surveying) DESCRIPTION: pix.m will plot the elevation data for some mountains. The elevations are
contained in the le mtns.mat. Matrices x and y contains x and y coordinates of each elevation reading. Matrix z contains the elevations. The rst part of the code sets up buttons that allows the user to change the perspective of the plots: the rst slider changes the azimuth and the second slider changes the elevation. The second part of the code cylces through each of type of plot.
CONTENTS:
creates the a ctitius elevations readings for a mountain contains the elevation reading of mountains the main program takes the elevation readings and smooths them out Written by: Brian Rose cont.m mtns.mat pix.m smooth.m
13.10.2 Listing 13.10.2.1
cont.m
[x,y]=meshdom(0:.1:2*pi,0:.1:2*pi); a=rand(1,5); b=rand(1,5); a=3.5.^(a+.1); b=3.5.^(b+.1); z=zeros(size(x)); for i=1:size(a,2) z=z+log(abs(sin(a(i)*x)))+log(abs(cos(b(i)*y))); end z=z+rand(size(z)); mesh(x,y,smooth(z,2)) figure(1)
13.10.2.2
pix.m
%script pix.m %will plot the elevation data for some mountains. %The elevations are contained in the file mtns.mat. %Matrices x and y contains x and y coordinates of %each elevation reading. Matrix z contains the elevations. %The first part of the code sets up buttons that allows
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.10 3dplot
13{41
%the user to change the perspective of the plots: the first %slider changes the azimuth and the second slider changes %the elevation. The second part of the code cylces through %each of type of plot. %clear screens, etc clear figure(1) clg %load the elevation data load mtns %set up the buttons for the 3D plots hAZ=uicontrol('style','slider','position',[.7 .95 .3 .05],... 'units','normalized','min',0,'max',360,... 'callback','[az,el]=view; az=get(gco,''val''); view(az,el);'); hEL=uicontrol('style','slider','position',[.7 .89 .3 .05],... 'units','normalized','min',0,'max',180,... 'callback','[az,el]=view; el=get(gco,''val''); view(az,el);'); hdef=uicontrol('style','pushbutton','position',[.88 .83 .12 .05],... 'units','normalized','String','Default',... 'callback','view(-37.5, 30)'); %do the 3D plots mesh(x,y,z) title('mesh(x,y,z)') xlabel('press any key to continue') pause meshz(x,y,z) title('meshz(x,y,z)') xlabel('press any key to continue') pause contour3(z) title('contour3(z)') xlabel('press any key to continue') pause meshc(x,y,z) title('meshc(x,y,z)') xlabel('press any key to continue') pause surf (x,y,z) title('surf (x,y,z)') pause surfc(x,y,z)
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{42
SAMPLES of MATLAB PROGRAMS
title('surfc(x,y,z)') xlabel('press any key to continue') pause surfl(x,y,z) title('surfl(x,y,z)') xlabel('press any key to continue') pause waterfall (x,y,z) title('waterfall (x,y,z)') xlabel('press any key to continue') %clear the figure window clg %do the 2D plots contour(x,y,z) title('contour(x,y,z)') xlabel('press any key to continue') pause pcolor (x,y,z) title('pcolor (x,y,z)') colorbar xlabel('press any key to continue') pause
13.10.2.3
smooth.m
function newz=smooth(z,weight) [m,n]=size(z); if ~exist('weight') weight=5; end newz=z; for i=2:m-1 for j=2:n-1 newz(i,j)=(z(i-1,j-1)+ end end
z(i-1,j+1)+
z(i+1,j-1)+
z(i+1,j+1)+ weight*z(i,j))/(4+weight);
13.11 zec
13.11.1 Description
SUBDIRECTORY: zec Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.11 zec
13{43 mesh(x,y,z)
4
x 10 1.2
1.1
1
0.9
0.8 15000 15000
10000 10000 5000
5000 0
0
press any key to continue
Figure 13.20: Sample plot from pix.m
SYNOPSIS: statistical analysis for heating energy of a building (Energy Management) DESCRIPTION: zec.m does a linear regression to nd a relationship between CONTENTS: function that performs linear regression main program contains heat and temperature data Written by: Brian Rose linregress.m zec.m zecdata
13.11.2 Listing 13.11.2.1
linregress.m
function [p,Rsquared,sigmabeta1]=linregress(x,y) %[p,Rsquared,sigmabeta1]=linregress(x,y) performs a linear regression on x and y. %p is a vector where y=p(1)+p(2)*x. % %[p,Rsquared,sigmabeta1]=linregress(x,y) will return R^2 as well as the standard %deviation in p(2)
%make x and y into row vectors
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{44
SAMPLES of MATLAB PROGRAMS
if size(x,1)<size(x,2) x=x'; end if size(y,1)<size(y,2) y=y'; end %print an error message is x and y are not the same lengths if size(x)~=size(y) disp('x and y need to be the same size') return end n=length(x) %linear regress. A contains a column of ones then the x values A=[ones(length(x),1) ,x]; %find p p=inv(A'*A)*A'*y; %get r, which is the residual r=y-(p(1)+p(2)*x);
%get SSE, SST, and Rsquared SSE=sum(r.^2); SST=sum((y-mean(y)).^2); sigmasquared=SSE/(length(y)-2); sigmasquaredbeta1=sigmasquared/sum((x-mean(x)).^2); sigmabeta1=sqrt(sigmasquaredbeta1); Rsquared=1-SSE/SST;
13.11.2.2
zec.m
Emperical linear relationship between heating energy and outdoor temperature: HeatEnergy = k1 + k2 Temperature
k1 and k2 may be found using regression features of Matlab. Regression improves as the correlation coecient(R-squared) value is found closer to '1.0'. zec.m le starts here: %script zec does a linear regression to find a relationship between %the heat energy and the outside temperature of a building. This script %uses data from the Zachry Engineering Center at Texas A&M %load the data
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.12 Stress/Strain Programs
13{45
load -ascii zecdata %extract only the columns we need energy=zecdata(:,11); temperature=zecdata(:,5); %do a linear regression. You can use the built in function polyfit %but that will not give Rsquared or delta. Note that delta is %the standard deviation of the slope. [p,Rsquared,delta]=linregress(temperature,energy); k1=p(1) k2=p(2) Rsquared delta %plot the results %plot the raw data plot(temperature,energy,'ro') hold on %plot the equation obtained from the linear regression x=[min(temperature) max(temperature)]; y=k1+k2*x; plot(x,y,'g-') hold off grid legend('raw data','linear regression') ylabel('Heat energy (MMBtu/hr)') xlabel('Temperature (F)') title('Heating vs. Temperature Plot')
Sample run of it zec.m: >> zec n =
744
k1 =
7.6999
k2 =
-0.0764
Rsquared = delta =
0.6639
0.0020
13.12 Stress/Strain Programs 13.12.1 Description
SUBDIRECTORY : Stress/Strain Programs Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
13{46
SAMPLES of MATLAB PROGRAMS
Draft
Heating vs. Temperature Plot 6
Heat energy (MMBtu/hr)
5
4
3
2
1
raw data linear regression
0 30
35
40
45
50 55 Temperature (F)
60
65
70
75
Figure 13.21: Sample output for zec.m
SYNOPSIS: stress and strain analysis for 2-D and 3-D elements DESCRIPTION: Two main startup commands are used for dierent analysis: 1. stressanalysis.m is a program which provides a menu driven interface to execute 2-D and 3-D stress/strain calculations. 2. stressdecomp.m creates a menu for 3-Dimensional analysis of stresses including options to Input Stresses, nd Normal and Shear stress components, Principal Invariants, plot the Principal Mohr's Circle with principal stresses and absolute max shear stresses, nd Mean and Deviatoric stresses, nd deviatoric principal invariants, and plot the Deviatoric principal Mohr's circles.
CONTENTS:
Program startup commands. stressanalysis.m - Start stress/strain analysis program. stressdecomp.m - Start stress decomposition program.
Print commands. elemprint.m circprint.m
- Save figure to file and ask to print. - Save Mohr's Circles and data to files.
2-Dimensional Stress/Strain Analysis.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.12 Stress/Strain Programs stress2dmenu.m planestress2d.m planestrain2d.m definitions.m principalangle.m maxshearangle.m plotelement.m plotprincipal.m plotmaxshear.m strainplotelement.m subplots2d.m transform.m rotelement2d.m plotcircle.m mohrcircle.m
13{47 -
Plane stress/plane strain menu options. Plane stress menu. Plane strain menu. Definitions of plane stress and plane strain. Principal stresses/strains and directions. Maximum shear stress/strain and directions. Plot of unit stress element. Plot of stress/strain principal values. Plot of stress/strain maximum shear values. Plot of unit strain element. Plot original, principal, & max shear elements. Transformation equations. Rotate element by an angle theta. Plot 2-D Mohr's Circle. 2-D Mohr's Circle with rotated angle.
3-Dimensional Stress/Strain Analysis. stress3dmenu.m - Stress/Strain menu options. stress3d.m - Stress menu. strain3d.m - Strain menu. plotelement3d.m - Plot of unit stress/strain element. plotcircle3d.m - Plot 3-D Mohr's Circle. Generalized 2-D and 3-D & Misc. functions. hlp.m - General help to use menus in stress programs. arrow.m - Draw a line with an arrowhead. parammenu.m - Menu driven way of entering variables. principal.m - Find Principal stresses/strains. straintostress.m - Convert from strain to stress. stresstostrain.m - Convert from stress to strain. 3-D Stress Decomposition. mkmatrix.m normcomp.m shrcomp.m invariant.m mndevcomp.m devinvariant.m -
Build a 3-D stress matrix. Normal stress component. Shear stress component. Principal invariants. Mean and Deviatoric stresses. Deviatoric principal invariants.
Written by: Melissa Holland
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{48
SAMPLES of MATLAB PROGRAMS
13.12.2 Sample Output:
How to access program: At Matlab prompt type: p=path path(p,'/bechtel/users1/graduate/hollanmm/matlab/') stressanalysis or stressdecomp Typing stressanalysis will cause the following menu to appear:
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13.12 Stress/Strain Programs
13{49
Figure 13.22: First menu encountered after starting stressanalysis Next, choosing 2-Dimensional Analysis from this menu brings up the next menu.
Figure 13.23: Menu encountered after clicking on 2-Dimensional Analysis button Finally, choosing Plane Stress button brings up the next menu(see next gure).
Figure 13.24: Menu encountered after clicking on Plane Stress button. These menus allow easy movement through the program. Clicking on other buttons in the previous menus will bring up other menus or ask for dierent information at the matlab prompt. Following are some examples which used stressanalysis program menus and input prompts to solve them. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{50
SAMPLES of MATLAB PROGRAMS
13.12.2.1 Example 1: Given: A state of plane strain exists at a point in a member, with the nonzero strain components xx = ;0:200, yy = 0:040, xy = ;0:900. Objective:
(a) Determine the principle strains in the (x,y) plane. (b) Determine the maximum shear strain in the (x,y) plane. (c) Show schematically the deformed shape of a rectangular element with the original undeformed element. (d) Plot Mohr's circle of strain.
Results: 2-D ELEMENT DATA Original Values: XX YY XY
= -0.2 = 0.04 = -0.9
Principal Values: (a)
S1 S2
= 0.827965 = -0.987965
Maximum Shear Values:
(b)
Avg Max shear
= -0.08 = 1.81593
2-D MOHR'S CIRCLE DATA Inputs: P1 P2
= (-0.2,-0.9) = (0.04,0.9)
C
= (-0.08,0)
Tmax Tmin
= (-0.08,0.907965) = (-0.08,-0.907965)
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
13{51
Principal Values: S1 S2
= (0.827965,0) = (-0.987965,0)
Principal Angle = 131.20 degrees
ORIGINAL Orientation
MAXIMUM SHEAR Orientation
PRINCIPAL Orientation
y y
y
x
x
x
Theta = 131.2 degrees
Theta = 86.2 degrees Theta = 0 degrees
Figure 13.25: Example 1(c): Original, Principal, Maximum Shear Stresses, and Deformed shapes. 2*Theta = 262.4 degrees 1
Tmax P2
0.8 0.6 0.4 Gamma xy/2
Draft
13.12 Stress/Strain Programs
0.2 0
2*Theta
S2 C
S1 Ex
−0.2 −0.4 −0.6 −0.8 P1 Tmin
−1 −1
−0.5
0
0.5
1
Figure 13.26: Example 1(d): Mohr's circle of 2-D stress.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
13{52
SAMPLES of MATLAB PROGRAMS
13.12.2.2 Example 2: Given: A rectangular strain rosette is cemented to a free surface of a structural member
made of alluminum alloy(7075 T6/ = 0:33 and E = 72.0 GPa). Under load, the strain readings are a = 0:00250, b = 0:00140, and c = ;0:00125 from which it may be found that xx = 0:00250, yy = ;0:00125, and xy = 0:000775. Note: a free surface means zz = zx = zy = 0, therefore, we will treat as a 2-Dimensional stress case. However, eventhough the stress acts as if 2-Dimensional, strain is 3-Dimensional in this case.
Objective:
(a) Determine principal stresses. (b) Determine the orientation of the volume element on which the principal stresses in the plane of the rosette act. (c) Determine maximum shear stress. (d) Determine the orientation of the volume element on which max acts. (e) Plot Mohr's circle of stress.
Results: 2-D ELEMENT DATA Original Values: XX YY XY
= 1.68668e+08 = -3.43396e+07 = 4.19549e+07
Principal Values: (a)
S1 S2
= 1.76997e+08 = -4.26685e+07
Maximum Shear Values:
(c)
Avg Max shear
= 6.71642e+07 = 1.09833e+08
2-D MOHR'S CIRCLE DATA Inputs: P1 P2
Victor E. Saouma
= (1.68668e+08,4.19549e+07) = (-3.43396e+07,-4.19549e+07)
Computing Literacy for Undergraduate Engineering Students
Draft
13.12 Stress/Strain Programs
13{53
C
= (6.71642e+07,0)
Tmax Tmin
= (6.71642e+07,1.09833e+08) = (6.71642e+07,-1.09833e+08)
Principal Values: S1 S2
= (1.76997e+08,0) = (-4.26685e+07,0)
Principal Angle = 11.23 degrees PRINCIPAL Orientation S2
ORIGINAL Orientation Sig y
MAXIMUM SHEAR Orientation Savg
Txy
y x
y
S1 x
Sig x
y x Tmax Theta = −33.77 degrees Savg
Theta = 0 degrees
Theta = 11.23 degrees
Figure 13.27: Example 2(b,d): Original, Principal and Maximum Shear Stresses.
13.12.2.3 Example 3: Given: Let the state of stress at a point be given by xx = ;120 MPa, yy = 140 MPa, zz = 66 MPa, xy = 45 MPa, yz = ;65 MPa, and zx = 25 MPa. Objective: (a) Determine the principal stresses. (b) Determine the maximum shear stress. (c) Plot Mohr's circle.
Results: 3-D MOHR'S CIRCLE DATA Inputs: X Y
Victor E. Saouma
= -120 = 140
Computing Literacy for Undergraduate Engineering Students
13{54
SAMPLES of MATLAB PROGRAMS 2*Theta = 22.46 degrees
Draft
8
x 10
Tmax 1
Tau xy
0.5
0
P1
2*Theta
S2 C
S1 Sigma x
P2
−0.5
−1 Tmin −5
0
5
10
15 7
x 10
Figure 13.28: Example 2(e): Mohr's circle of 2-D stress. Z XY XZ YZ
= = = =
66 45 25 -65
Principal Values: (a)
S1 S2 S3
= (180.207,0) = (40.0573,0) = (-134.264,0)
Maximum Shear Values: Tmax1 Tmax2 Tmax3 (b)
= (-47.1035,87.1608) = (22.9714,157.236) = (110.132,70.0748)
Tmax = 157.236
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
13{55
Draft
13.12 Stress/Strain Programs
Tmax2 150
100
Tmax1 Tmax3
Tau xy
50
S3
0
S2
S1 Sigma x
−50
−100
−150
−150
−100
−50
0
50
100
150
200
Figure 13.29: Example 3(c): Mohr's circle of 3-D stress.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
SAMPLES of MATLAB PROGRAMS
Draft
13{56
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
Part III
MODULE III (1 cr)Fortran 90
Draft
Draft
Chapter 14
Day I: INTRODUCTION For a better understanding of fortran, this chapter will begin with a brief overview of the architecture of a computer, role of its software, and nally status of fortran. 2 The next section will be devoted to a brief review of fortran (with which the reader is asumed to have a certain familiarity), highlight those features which may not have been covered in an introductory course, and terminate with recommendations for programming style and documentation. 1
14.1 Introduction
14.1.1 Computer Architecture and Software 14.1.1.1 Computer Hardware
Digital computers are concerned with the processing of data1 abd their basic architecture has seen little if any fundamental changes since the conceptual model rst proposed by Von Neumann in a landmark paper in 1946:
3
Storage: of data and commands: Data as well as commands are internally stored in binary form (0 or 1). The most elementary unit of data is the bit. A group of eight bits form a byte. A byte can have 28 = 256 dierent values, and is
1 Early
usually used to store a character (extended ASCII). In most present day computers, four bytes form a word. Early PC's had 16 bit word, most other computers have 32 bits, and supercomputers have 64 bits. on Engineers used extensively analog computers.
Draft
14{2
Day I: INTRODUCTION Storage is accomplished on any one of the following:
1. cache memory, extremely fast, it acts as a buer between the CPU and the core memory. 2. Core memory, very fast, usually around 8 Mb (106 ) bytes for PC's and at least 32 Mb for workstations. 3. Disk space, about 1 Gb. 4. Other peripherals such as magnetic tapes, CD-ROM, scanner, laser printer. Most computers have a Virtual Memory, that is when core memory is full, data is temporarily stored on disk by the operating system. Central Processing Unit or CPU: The heart of the computer is the CPU or central processing unit. It is the device which performs actual data processing. For instance it may take the contents of two speci ed locations in memory, add them together and return the result to a third location. Operands are temporarily stored in registers in the CPU. The CPU has an arithmetic and a logic unit(s) to perform various basic operations (such as add, multiply, substract, divide, and others) on operands stored in the registers. It was found that in most cases only a limited number of CPU operations were triggered. Hence, most modern CPU architecture are based on RISC architecture or Reduced Instruction Set Computers, where we have CPU capable of performing fewer operations but much faster2 . Instructions are orders on how data is to be manipulated: The instructions control directly the movement of data words between the main memory and the registers of the CPU. The instructions are stored themselves just like data in the main memory which is partitioned. In most computers, a special register points to the location in memory which contains the next instruction to be executed. When the current one has been executed, the next one is fetched from memory, decoded and its orders executed. This process can be streamlined by vectorizing the operations through a pipeline, this is done on SuperComputers with vectorization. Through networking, you now can have as many computers on your workstations as you have windows. 2 Hence
a program compiled on a RISC machine is likely to generate a much bigger object le.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
14.1 Introduction
14{3
Finally, you may have access to multiple CPU on one computer, or better yet multiple
CPU on multiple computers all through you workstation. Input/Output: has drastically changed over the years: Access to computers: 1. Computing started as one mainframe executing only one program at a time. The program was either punched on a tape, or later on cards. 2. In the early 70's we had one mainframe (such as IBM) or minicomputer (such as VAX), with numerous concurrent users connected through terminals. 3. Later came the workstations in which each user has his/her own computer. 4. Finally, with the new generation of workstations/software, a user can have access to more than one computer or CPU. A typical modern workstation has: 1. a 1,012 by 1,012 8 bit graphical display (i.e a resolution of 1; 012 1; 012 pixels, each one capable of assuming up to 28 = 256 colors). 2. A keyboard, and a mouse 3. Unix Operating system 4. At least 12 Mb of core memory 5. 200 Mb of disk space 6. Access to a local area network (usually ethernet) 7. X based window management and access to laser printer, plotter, CD-ROM, tape drive, digitizer, scanner, speaker, modem. Computers are often networked together, a commonly used standard is ethernet. Increasingly the distinction between PC and workstation is being blurred. Currently, most new PC's are computationally more powerful than the immediate past generation of workstations. 5 Major distinction between PC and Workstation is highlighted by table 14.1.
4
14.1.1.2 Computer Software
For the computer to operate, it must also have: Operating System: which is a collection of programs to control the operation of the hardware and application programs. Early on each computer vendor had its own operating system. Most recently, Unix3 has emerged as the uncontested de facto standard operating system for workstations, 3 Unix
is a trademark of AT&T.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
14{4
Day I: INTRODUCTION Feature PC Workstation Processor Intel Motorola Memory 8-16 Mb 32-64 Mb Operating System Windows 95/NT Unix/Motif RISC N Y Monitor 15"-17" 19"-21" Resolution 1024x1024 1024x1024 Bit Planes 8 8-24 Graphics Accelerators Y Y Networking Novell Ehternet Editors Word Vi, Emacs, Crisp Virtual Memory N Y Primary Application Everything Scienti c Computing Source of Software Microsoft Public-Domain, GNU, Vendors Graphics Open GL Open GL, X Table 14.1: PC Vs Workstation
mainframes, and supercomputers. It is also increasingly used on PC's for scienti c computing (through Linux). Unix is for the most part written in C, and comes in two major avors: Berkeley Unix, or AT&T System V Unix. Window Management: for workstations Early on (about 1980) each vendor had his own proprietary windowing management. Through original funding from IBM, and Digital, MIT has developed X as a uni ed windowing system for workstations through the Athena project. X was found to be very powerful, portable, but relatively cumbersome to use. Hence around X two major competing products have evolved: Motif: which has been developed by the Open Software Foundation, (OSF) which groups most major vendors with exception to Sun. OpenWindow: developed by AT&T and Sun. Note that each one of the two can also be used on the other. Numerous software have been modi ed to run under X and its Graphical User Interface (GUI). Low Level Language: such as assembler. High-level languages: such as fortran. Fortran source code is written in an ASCII le, the compiler will then translate it into an object-code, and nally object-codes are all put together by the loader or linker. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
14.2 From Source to Binary
14{5
\Very High-level languages" MATLAB, Mathematica, IDL, MathCad.
14.1.2 Fortran Past, Present, and Future
Despite numerous challenges, fortran remains the uncontested language of choice for scienti c/engineering programming. Eventhough over 34 years old, fortran has continuously been rejuvinated through revisions of its standards: Fortran (FORmula TRANslator) was originally developed by John Backus from IBM in 1957. As the rst ever high level language, it was simple to learn and use. In 1966 Fortran was standardized by ANSI (American National Standard Institute) and resulted in Fortran 66 (or sometimes called Fortran IV). Again in 1977 the Fortran standard was revisited and modi ed to account for either the ellimination of some features, or the addition of others. Many manufacturers have developed their own extension to the standards. While in many cases it made programing easier, in most cases it was an attempt to \capture" users to keep their code on a particular machine4 . Recently, Fortran underwent a major revision which resulted in Fortran-90. For economic reasons, it was made upwardy compatible (i.e it recognizes most of Fortran-77 syntax, even though the use of many of them is discouraged). Fortran-90 not only addresses some of the features found in more \modern" languages such as C, but is also designed to facilitate the full exploitation of modern supercomputers/workstations.
14.2 From Source to Binary There are two major steps in creating an executable code: Compiling: which takes as input the source code(s) written (in ASCII) by the developped and converts it into an object code. Usually, the former has extensions such as .f, .F or .for, and the later .obj. Linking: Which takes the object les written by the user, and link them not only among themselves bu also with standard (fortran) and non-standard (such as graphics) libraries. This process results in an executable which on Unix is by default called a.out, or given an extension .exe in Windows. 4 You should never use non-standard Fortran statements. 6
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
14{6
Day I: INTRODUCTION
14.3 Sample Example 7
To begin with, use your favourite editor to create the following le ello.f5
program Hello print *, 'Hello, world' end program Hello
8
Next save the le, and type
f90 hello.f a.out
14.4 Fortran Compilers 14.4.1 Compilers 9
In the Bechtel Lab, you have access to the fortran compilers listed in Table 14.2. Compiler Debugger Description f77 f90 f77 xlf90
Sun Workstations None
Fortran 77 Nag Fortran 90
xldbx xldbx
Fortran 77 Fortran 90
dbx
IBM Workstations PC
MicroSoft Power Station Fortran Compiler Table 14.2: Fortran Compilers in the Bechtel Lab It should be noted that the Fortran-90 compiler f90 on the Sun is only a \pseudo-compiler" in the sense that the code is rst internally translated into C and then compiled with a C compiler. This was one of the earliest Fortran-90 compilers developed by the Numerical Analysis Group in the UK until a true Fortran-90 is developed. 11 Debugger will be separately discussed in a subsequent lecture along with the Make command (which enables the programmer to easily keep track of modi ed les in the process of developping a large code). 12 The general form of the f90 (or f77) command is: 10
> f90 list-of-options list-of-files-and-libraries
5 This classic example was rst introduced by XX & xx in their introductory book on C, and has since then become the opening example in most introductory computer language tutorials.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
14.5 Flow Charts, Macro-Code
14{7
14.4.2 File Extensions The following le extensions are recognized by most compilers: .f, .for Standard fortran input le. .F Fortran le with ccp directives which will be run through a ccp preprocessor (more about this later). .o Object le. an extension of .o instead of the .f, .F or .for. 13
14.4.3 Workstation Compilers 14 On the Sun or IBM workstation, the simplest way to compile your code is to type
As in most programs, the fortran compiler can be invoked with a number of options. Those are too numerous to list, and most of them are only used in very special cases. Table 14.3 lists the most commonly used ones, additional information may be obtained through the man command. 15
14.4.4 Compiling with Microsoft Power Station
14.5 Flow Charts, Macro-Code
It is highly advisable that prior to programing, a owchart describing the program be prepared. 17 Fig. ?? illustrates the symbols commonly associated with various operations.
16
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Day I: INTRODUCTION
Draft
14{8
-C -g -o
-k -O -O2 -O3 -p -pg -v -w
Highly Recommended Performs run-time checking of array bounds and character substring expressions. Produces debug information. Names the executable le
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
Chapter 15
WEEK 1: Basic Operations 15.1 Background 15.1.1 Preliminaries
15.1.1.1 Program Layout 1
The layout of a program should be as follows
program hello_world .... end program hello_world
15.1.1.2 Characters 2
Acceptable characters in fortran are shown in Table 15.1 a-z, A-Z, 0-9,
& ! ;
characters Continuation Comment; Line following ! is ignored by compiler Separator Table 15.1: Characters
Statements can start in column 1 and extend up to 2640 characters including blanks, or 40 lines.
3
15.1.1.3 Variable Types 4
The following variable types are recognized by fortran
Draft
15{2
WEEK 1: Basic Operations
Integers they usually have a range from ;2n;1 to 2n;1 + 1, where n is the word size (for 16
bits, the range is from -32768 to +32767). Real is a decimal oating point characterized by a mantissa and an exponent such as 1.56E-03, that is 1:56 10;3 , or 123.4567 On 32 bit computers, real have 7 signi cant digits. Double Precision A real number which is stored in two words. 1.56D-03, that is 1:56 10;3 , or 123.45678901234 On 32 bit computers, double precision reals have 14 signi cant digits. Complex (12.,5) represents (12+5i). Logical (.TRUE. or .FALSE.) String 'this is a long string' 5 Note that integers and reals are stored in one word which consists of 32 bits, a double precision real uses two words.
15.1.1.4 Labels 6
A label is a numeric pointer to a statement
delta=b**2-4.*a*c if(delta>0)go to 100 ! Note this form of branching should be avoided .... 100 continue ! 100 is the label
Usage of labels (and correspondingly of assigned and conditional branches) is strongly discouraged unless unavoidable.
7
15.1.2 Data Declaration Type Statement: integer,
real, double precision, complex, logical, character. Rea(0:100,-1,10). type should be
member that the range need not start from 1, i.e real prefered over dimension. ! Declare variables real :: alpha, one, x, y, z, length integer :: i, kounter, kode double precision :: w character :: file_name, output_file logical :: test
Implicit Statement: There are three possibilities: 1. By default in fortran all variables are real except those beginning with letter in the range I to N unless otherwise declared. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
15.1 Background
15{3
Draft
2. Stipulate implicitly all the variables beginnig with a certain letter as being of a certain type implicit real*8 (a-h,o-z) ! declare all reals to be double precision
3. Explicitly declare all the variables through implicit none real :: x, y, ...
This is by far the most suitable form of declaration as it will facilitate program debugging (where 1, l, i, L may be easily confused and create debugging nightmares). Initialization: Often time a variable may have to be initialized to a certain value. This can be done in either two ways: 1. Using the parameter statement integer,parameter:: year=1996 real,parameter::pi=3.141592654,one=1.0e+00 complex,parameter :: i=(0,1)
and during execution, these constants can not be rede ned (as a matter of fact, substitution id done during compilation). 2. Through the type statement declaration integer:: year=1996
Contrarily to the previous example, variable year can be over-written during execution. 8
Logical or \Boolean" variables can be declared
logical :: on, off, correct, wrong, small, large, true, false
those values (stored in only one bit) can only take the values .true. or .false. on=.true.; false=.false.; small=.true.;large=.false.
9
Logical or \Boolean" variables can be declared
logical :: on, off, correct, wrong, small, large, true, false
those values (stored in only one bit) can only take the values .true. or .false. on=.true.; false=.false.; small=.true.;large=.false.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
15{4
WEEK 1: Basic Operations
15.1.3 Basic Operations
15.1.3.1 Assignment Statement 10
The basic assignment statement is of the form
variable=expression
which means: 1) evaluate mean \equals". x=x+y pi=3.14159 feet=12.*inches
expression
rst, and 2) assign it to
variable.
Thus = does not
| evaluate x+y, and then assign result to x | set the value of pi
15.1.3.2 Arithmetic Statements 11
Basic arithmetic operations are shown in Table 15.2 + Addition ; Subtraction Multiplication Exponentiation = Division Table 15.2: Basic Arithmetic Operations
Order of operations: 1) exponentiation; 2) multiplication, division; 3) addition, substraction. For example A+B**2/C is equivalent to A+((B**2)/C) Truncation occurs for integer division: 12
8/3 = 2
15.1.3.3 Logical Operators Logical variables can be operated by operators in which .not. negates or changes the logical value of the single variable it operates on. 14 Other operators are binary and are placed between two logical variables and used to compare their states. 15 Order of precedence is .not., .and., .or., .eqv. and .neqv. Parenthesis can be used. 16 A complete \truth table" for logical operators is shown in 15.3. 13
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
15.1 Background
Draft
on .true. .true. .false. .false.
15{5 off .true. .false. .true. .false.
on.and.off .true. .false. .false. .false.
on.or.off .true. .true. .true. .false.
on.eqv.off .true. .false. .false. .true.
on.neqv.off .false. .true. .true. .false.
Table 15.3: \Truth Table" for Logical Operators
15.1.4 Intrinsic Functions Common arithmetic intrinsic functions are shown in Table 18 Table 15.5 lists intrinsic functions that inquire about the numerical environment. 19 Table ?? lists intrinsic functions that manipulate the numerical characteristics of variables in the real model. 20 An important feature of all of these intrinsic functions is that they are generic and may be used to obtain information about any kind of integer or real supported by the Fortran 90 implementation. 17
15.1.4.1 Character Expression 21
The only allowed character expression is the concatenation operator //
c='Student Name' d='John Smith' e='c//': '//d
will give e='Student
Name:
John Smith'
15.1.4.2 Relational Operators 22
23
The following relational operators can operate on numeric expressions and variables < Less than <= Less than or equal to == Equal to = = Not equal to > Greater than >= Greater than or equal to A logical variable can be set equal to a logical expression
logical:: converged ; real::epsilon=1.e-03 ...
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
15{6
WEEK 1: Basic Operations Function
sqrt(x) abs(x) sin(x) cos(x) tan(x) sinh(x) cosh(x) tanh(x) asin(x) acos(x) atan(x) exp(x) log(x) log10(x) int(x) real(i) dble(x) cmplx(x) cmplx(x,y) aimag(x) anint(x) nint(x) ceiling(x) floor(x) sign(x,y) mod(i,j) max(x,y,...) min(x,y,...) max(x,y,...) minval(ax) maxval(ax) product(ax) sum(ax) len(strx) len trim(strx) trim(strx) index(strx,stry)
Description Square root of x Absolute value of x Sine of angle x (in radians) Cosine of angle x (in radians) Tangent of angle x (in radians) Hyperbolic sine of x Hyperbolic cosine of x Hyperbolic tangent of x Arcsine of x Arcscosine of x Arctangent of x e raised to the power x Natural log of x Common log of x Converts a real into an integer Converts an integer into an integer Converts x to double precision x + 0i x + yi Imaginary part of x Round x to nearest whole number Round x to nearest integer Least integer x Greatest integer x Transfer sign of y to jxj Remainder or modulo functio Maximum of x; y; ::: Minimum of x; y; ::: Maximum of x; y; ::: Minimum value in array ax Maximum value in array ax Product of values in array ax Sum of values in array ax Length of character string strx Length of string strx without trailing blanks strx without trailing blanks Position of stry in string strx
Table 15.4: Common Arithmetic Intrinsic Functions Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
15.1 Background
Function
15{7
digits(x) epsilon(x) huge(x) minexponent(x) maxexponent(x) precision(x) radix(x) range(x) tiny(x)
Description q for an integer argument, p for a real argument b1;p for a real argument Largest in the integer or real model Minimum value of e in the real model Maximum value of e in the real model Decimal precision (real or complex) The base b of the integer or real model Decimal exponent range (real, complex, or integer) Smallest positive value in the real model
Table 15.5: Intrinsic Numerical Functions for Numeric Inquiry
Function
exponent(x) fraction(x) nearest(x) rrspacing(x) set exponent(x) spacing(x)
Description Value of e in the real model Fractional part in the real model Nearest processor number in a given direction Reciprocal of relative spacing near argument Set the value of e to a speci ed value Model absolute spacing near the argument
Table 15.6: Numeric Manipulation Functions
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
15{8
WEEK 1: Basic Operations
converged=abs(error)<epsilon ! if rhs is true, converged=.true. otherwise it is .false. if(converged)xf=x ! set xf equal to x only if converged=.true.
15.1.5 Control Statements 15.1.5.1 Branches
Branches came in two types: Unconditional go to should be used as scarcely as possible, unless you want your code to look like a spaghetti plate. Assigned go to: (not to be confused with the unconditional go to), is seldom used but can be quite powerful. It is actually written in two parts: assign and then go to 24
go 10 go go 20 go
to (10,20,30) kode ! go to 10 if kode is negative, 20 if zero, and 30 if positive x=x*x to 40 to 40 x=2.e+00*x to 40 ........ 40 continue
15.1.5.2
if
Statement
If statements come in two forms Logical if in which a single statement is executed if the operand is true 25
if(grade>3.)letter_grade='A' ! Note that letter_grade is a character if(converged)xf=x ! Note that converged is a logical
Block if is to be used when multiple statements may have to be executed, or if a series of if checks must be performed. An if statement invoking a block can be given a name. It is highly recommended to properly indent a block if (usually by two extra spaces). if(i=2)then k=k+3 elseif(i.eq.4)then ! Note the old form of .eq. inherited from fortran 77 ! and which should be replaced by = k=2*k else k=0 endif ... grade: if(average>3)then
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
15.1 Background
15{9
let_grad='a' elseif(average<3.and.average>2)then let_grad='b' endif grade
15.1.5.3
case
To branch into dierent parts according a very simple criterion we use the case statement. It can choose a suitable case for a scalar argument of type integer, logical or character.
26
select case (ivar) case (:-1) write *, 'negative number' case (0) write *, ' zero' case (1:9) write *, ' digit ', ivar case (10:99) write *, ' number ', ivar case default write *, ' too great number' end select decades: select case (nyear) case(:1980) decade='past' case(1980:1989) decade='1980-1989' case(1990:1996) decade='1990-1996' case default decade='future' end select decades
!
all negative numbers
!
zero case
!
one-digit number
!
two-digit number
!
all remaining cases
Note that overlapping arguments are not permitted. This means that one single argument may not satisfy more than one of the cases of case. The default case does not have to be included. If no valid case is found the execution will continue with the rst statement after the end select. 28 It is recommended to use the case instead of an assigned or computed go to statement, or an arithmetic if statement.
27
15.1.5.4
do
loops
There are essentially two type of do loops Endless Loop (do while) is a loop in which a sequence of statements are executed as long as a certain condition isis met. It has the form do while logical expression statement 1 29
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
15{10
WEEK 1: Basic Operations
... statement n end do
Iterative loop do involves initialization of a counter, automatic increment of the counter by an increment at the end of the loop, and repetition of the statements within the loop as long as the counter does not exceed the user speci ed upper value. do index,limit,increment statement 1 ... statement n end do
where index, limit and increment are the running index (which can not be overwritten within the loop), the upper limit, and the increment. If the increment is not speci ed, the default is one. index, limit and increment can all be either integers or reals, positive and/or negative. 30 31
A loop may be exited through exit A loop may also be given a name
program mean implicit none real::f_c,sum,mean integer::ndata sum=0.0 count: do read*, f_c if(f_c<=0.)exit sum=sum+f_c ndata=ndata+1 end do count mean=sum/real(ndata)
32
Finally, do loops can be nested.
15.1.6 Input/Output
15.1.6.1 Devices Default Devices/Read/Write Units must be assigned to input and output devices. On most systems, they are 5 for the keyboard, and 6 for the screen. 33 Hence, by default, the basic format of read write formats becomes read*, a,b,c print*, a,b,c
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
15.1 Background
15{11
Selected Input/Output Devices In the most general case, input data will be read from,
and output writen into user speci ed les. Thoose les must rst be de ned through the open statement which takes the following form open (unit=unit number,file=' le name', status=status) where unit number is an integer number assigned to the device, ' le name' is a character string giving the le name, and status is a character string which can be 'old', 'write', or 'read'.
15.1.6.2 Formated I/O 33 The format for the read statement is as follows read(unit number,format label)variable list where unit number is the device number through the open statement, and format label is the format label as de ned below.
speci ed
34 The format for the write statement is as follows write(unit number,format label)expression list where unit number is the device number ed through the open statement, and format label is the format label as de ned below. 35
speci-
Note that we can use the default devices for both read and write
open(unit=1,file='input.dat') open(unit=2,file='output.dat') write(*,*)' About to start reading from unit 1' ! May be placed for debugging purposes read(1,800)a,b,c write(2,900)a,b,c
Format De nition A format can be de ned in anyone of the following ways: Statement Label: referring to a format statement 900
write(6,900)A format(f10.2)
Character Variable provides a exible way to dynamically de ne the format: character*(*)form1, form2 parameter (form1='(f10.3)', form2='(f10.4)') ... if(...)then write(6,form1)a else write(6,form2)a endif
Edit Desciptors: Beside the familiar Iw, Fw.d, and Ew.d forms, there are a couple of others with which you should familiarize yourself: Iw.m speci es the width of the eld (w) and the number of digits to be printed (m); i.e I5.3 for 99 will be printed as bb099
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
15{12
WEEK 1: Basic Operations
mPEw.d is a scale factor which should be used with the E format exclusively (eventhough
you can use it with the F format). It will print m signi cant digits to the left of the decimal point. Hence x = 123:5 103 will be printed as .1235E+06 with e10.4, and 1.235E+05 with 1pe10.3 Gw.d is a general format to be used when magnitudes are not known in advance, and where an F conversion is preferred where possible to an E format. Tabulation: is an input and output eld which can take anyone of three forms: Tn, TRn and TLn. Respectively they mean that the next part of the I/O should begin at position n (global), or n to the right or left of the current position (relative). Its use should be encouraged for tabulation of results.
15.1.7 Portability
Following are some additional guidelines which should be followed to ensure portability of your program: 1. Don't ever use variable names which exceed 6 characters. Be careful as some compilers may accept them, but would internally truncate any character following the sixth (hence temperin and temperout would be treated as one single variable (temper) 2. Even if the compiler allows it, do not insert more than one statement per line. Avoid the non-standard semi-colon (;) as a separator 3. Do not insert in-line comments following your fortran statement and the exclamation mark (!) 4. For logical constants, use the full descriptor .true. and .false. rather than .t. and .f.
5. Do not use mixed-mode relational expressions such as x=a/I 6. Do not use non-integer subscript in arrays such as in x(a/b)=..., instead round it explicitely as in x(nint(a/b))=... 7. Do not use the do while or do until or most importantly the do end do constructs. They are not (yet) part of the standard. 8. Do not use the read or write statements without specifying a unit. 9. Do not use underscore or currency symbol $ in variable names.
15.1.8 Style
1. Nested loops should be arranged such that the inner most loop should reference the rst subscript, and the outer most loop, the last subscript.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
15.1 Background
15{13
do
k=1,50 do l=1,20 a(l,k)=b(l,k)+c(l,k) end do end do
2. All common blocks and sub-system control variables de ned via parameter statements are de ned in include les. The naming convention for include les is based on their contents; include les containing common blocks have the extension .cmn and include les containing parameters have the extension .par. The dierent extensions allow the developer to determine the contents of an include le without using a text editor. 3. Fortran is not a case sensitive language. However, lower case code is allowed. All source code should be in lower case, this is much easier in a Unix environment which is case sensitive, with the exception of the following exceptions: Global or common variables begin with an upper case letter; all other characters are lower case. Variables de ned via parameter statements are all upper case. This allows the developer to quickly determine where a particular variable comes from. 4. All variables should be declared; and the FORTRAN standard for variable types should be ignored. To insure that all variables are declared the -u option should be used when the source code is compiled on the Sun. Explicit declaration of all variables eliminates typographical errors and the omission of function subroutine type declarations, both of which are fairly tricky bugs to locate. 5. Variable names should be selected in a logical manner by choosing descriptive names. All variables should have no more than 6 characters. Also a common "syntax rule" should be adopted where a single basic variable name is employed with dierent pre xes depending on its usage in the program: (a) Pre x i,j, or l should be used to indicate a DO loop variable (b) Pre x k will indicate a counter (c) Pre x m will indicate a maximum value (d) Pre x n will indicate a given number For example ipoin, npoin, mpoin will indicate a particular point, number of points, and maximum number of points respectively. 6. All do loops should end on separate continue statements and the code between a do statement and the corresponding continue statement should be indented. This is more a matter of readability than anything else, but often comes in very handy when examining a particularly long do loop. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
15{14
WEEK 1: Basic Operations
7. Ideally, a subroutine should have only one return statement. This is particularly true with long subroutines where multiple return statements make it dicult to follow the logic of the subroutine. It can be especially dicult to debug a subroutine with multiple return statements and for these reasons the use of one return statement per subroutine is strongly advocated. If there are multiple conditions that require returning to the calling subroutine the eect of multiple return statement can be duplicated with one labeled return statement and goto statements using the label corresponding to the return statement. The statement label will appear in a compiled listing with cross-references easily allowing a programmer to pinpoint the return conditions. 8. Ideally, the numbers used as statement labels in a given subroutine should appear in increasing order and the numbers should be evenly spaced. The statement labels found in most subroutines are multiples of ten. When there is a statement label associated with the return statement this statement label is generally 999. Statement labels associated with format statements are generally numbers between 700 and 990, inclusive. Statement labels between 700 and 790 are associated with debug prints; statement labels between 800 and 890 are associated with echoing input data; and statement labels between 900 and 990 are associated with error, warning, and informational messages written to the formatted output le. Associating a particular number or range of numbers with a certain type of format statement makes it easy to locate and/or recognize these statements when examining a compiled listing with cross-references. 9. Insert blanks in long expressions to facilitate their reading 10. Whenever there is a division, perform a check to determine whether the divisor is zero. 11. The use of extensions to the FORTRAN 77 standard should be avoided at all costs for the sake of portability. Extensions to the standard are generally identi ed in some way in the FORTRAN manual for a given compiler. If in doubt, consult the manual to be sure.
15.1.9 Debugging
1. Learn how to use your local debugger. 2. If possible, compile your program on another computer/compiler. You will be surprised to nd out how \forgiving" your computer may be. 3. The most common causes of Fortran errors are: (a) In nite loops (b) Division by zero (c) Erroneous array subscripts causing a location outside the allowable range. i. If it addresses a memory location associated with instruction, then a sudden crash may result.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
15.2 Assignment
15{15
ii. If it addresses another variable location, then that particular one will be overwritten. As the program will not crash, this error is more dicult to locate unless you specify array subchecking as a compiler option. (d) Use of uninitialized variable. You can not always assume them to be zero.
15.2 Assignment
15.2.1 Beam on Elastic FOundation De ection
The defelection of a beam, length L, and exural rigidity EI on elastic foundation with stiness k by a central point load P is given by (L ; x)) ; sin( L)icosh( x) cos( (L ; x))] h v = 2P [sinh( L) cos( x) cosh( (15.1) k sinh2 ( L) ; sin2 ( L) q
where = 4 EIk Find the de ection for x = 0, 2, and 5 m for P = 100 kN, k = 4 103 kN/m2 and EI = 106 kN/m2
15.2.2 Quadratic Equation
Write a program to read in three numbers a; b and c, assumed to be the coeceints of the quadratic equation ax2 + bx + c = 0 (15.2) and calculate and print the roots. Account for the three possibilities 1. Two dierent real roots 2. One (double) root 3. A pair of complex conjugate roots
15.2.3 Statistical Analysis
Retrieve (through anonymous ftp to bechtel) the following set ftp/pub/Matlab/set1.dat. It contains results of concrete compressive strength fc0 for two dierent ready mix companies. Determine the Mean, Standard Deviation, Coecient of variation, Skewness, and Kurtosis. (Refer to MATLAB lecture notes).
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
WEEK 1: Basic Operations
Draft
15{16
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
Chapter 16
WEEK 2: ARRAYS 16.1 Background 16.1.1 De nition
An array is de ned to have a shape given by its number of dimensions, called rank1 and extent for each one of these.
1
16.1.2 Declaration Whereas the declaration of scalar quantities is optional (unless we use implicit arrays must be declared. For example
2
none0,
all
real, dimension(20):: force real, dimension(20,20):: k
Alternatively we can use the following format real :: force(20) real :: k(20,20)
It is conventially assumed that the rst subscript of a two-dimensional array represents the row, and the second the column. 4 In fortran, arrays are stored column-wise, i.e. internally all arrays (no matter what their rank is) must be stored sequentially as a vector, hence stiffness will be stored as
3
k(1,1),k(2,1),...,k(20,1),k(1,2),k(2,2),...k(20,2),k(1,3),...k(20,20)
5
Array subscript can be negative, zero, and/or positive:
{\tt real:: vector(-10:22)}
1 Note
that the rank of an array is the number of dimensions and has nothing to do with the mathematical rank of a matrix.
Draft
16{2
WEEK 2: ARRAYS
is an example of one dimensional array where the subscript may range from -10 to +22. {\tt real dimension(-10:25, 20:40):: grid}
is a two dimensional array.
16.1.3 Array Initialization Arrays can be initialized in a compact Implicitely for an entire array 6
real, dimension(5)::load=0.0 ! vector load is initialized to zero
Explicitely For each array value
real dimension (5):: load=(/10., -20., 15., 25, -32./)
Do loop Through a loop
real, dimension(3)::load=(/(2*i,i=1,3) /)
Note that speci cation of constants must be enclosed in \(/" and \/)" delimiters.
16.1.4 Array Constructors 7
Assignments statements for array elements can be performed as for scalar
k_struc(25,3)=k_elem(1,3,5)
8
Alternatively, we can \construct" the elements of a one dimensional array using a shorthand:
load=(/10., -20., 15., 25, -32./)
is equivalent to
load(1)=10.; load(2)=-20.; load(3)=15.; load(4)=25; load(5)=-32.
16.1.5 Array Sections Sections of arrays can be separately accessed. Array sections select part of an array consisting of regularly spaced array elements taken parallel to the dimensions of the source array. 9
real, real, real, real, real, real,
dimension(6,6) dimension(3,3) dimension(6) dimension(6) dimension(6) dimension(36)
k_node_i k_left_column k_top_row k_linearized k_diagonal
:: :: :: :: :: ::
k k_node_i k_left_column k_top_row diagonal k_linearized
= = = =
k(1:3,1:3) k(:,6) k(1,:) pack(k,.true.) ! pack is an intrinsic function which ! collapses k into a vector = k(1:36:6)
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
16.1 Background
16{3
16.1.6 Dynamic Memory Allocation 10 Dynamic allocation is useful when reading a data le of a size that is not known until runtime. The array would need to be de ned as allocatable. This is done by simply adding allocatable to the declaration line, with the dimensions speci ed as \:". Next, the array must be allocated once the dimensions are known, but before anything is read into the array. A second argument can be used with the allocate routine, in which the error status is set according to the success of the call. This should always be checked, to be sure there was enough memory for the allocation. real, dimension(:,3), allocatable :: nodal_coordinates integer, dimension(:,2), allocatable :: element_connectivity integer :: error read*, number_nodes, number_elements ! Get the matrix dimensions allocate(nodal_coordinates(number_nodes, 3), stat = error) allocate(element_connectivity(number_elements, 2), stat = error) if (error .ne. 0) then print*, "Allocation failed" stop endif read*, nodal_coordinates read*, element_connectivity ... ! Use arrays ... deallocate(nodal_coordinates, element_connectivity) ! Release memory when finished
16.1.7 11
do
Loops & Vector Operations
The do loops is often unnecessary for most array operations 1. Rows, columns, matrices, etc. may be assigned to each other as long as the dimensions are the same. All of the following assignments are valid: ! Initialize A and B to dummy arrays of the same dimension integer, dimension(5) :: a = (/ 1, 2, 3, 4, 5 /) integer, dimension(8) :: b = (/ 1, 2, 3, 4, 5, 6, 7, 8 /) integer, dimension(8) :: c ... c = b ! set vector c equal to vector b a = b(4:8) ! Assign to a the 4th through 8th elements of b b(3:7) = c(2:6) + a
2. For example, if we have an array (any dimensions) and want to initialize it to any scalar, say 0:0, rather than \walking" through each element with nested do loops, we can simply say \matrix = scalar", and every element of \matrix" will then be assigned the value of \scalar". 3. Some do loops can be replaced with a call to the dot product intrinsic function. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
16{4
WEEK 2: ARRAYS
Draft
real, dimension(4) :: a, b c = dot_product(a,b)
4. Arrays or matrices can be accessed in non-ascending order, and portions can be extracted using appropriate subscripts. To repeat the dot product of the previous example with array b reversed, the following could be done: c = dot_product(a,b(n:1:-1))
16.1.8
where
Construct
This is essentially an extension of the if, then, else constructo for scalars, it is a powerful way to check/modify each and every cell in an array.
12
real, dimension(5,20) ::x,y real, dimension(-2:2,20) ::z : z = 4.0*y*sqrt(x) where ( x >= 0.0 ) z = 4.0*y*sqrt(x) elsewhere z = 0.0 end where
16.1.9 Intrinsic Functions Fortran 90 has over 100 intrinsic functions, the most important ones operating also on arrays are listed below. c 1993, Note that this section is adapted from Fortran 90 for the Fortran 77 programmer by Bo Einarsson2 and Yurij I Shokin3. Permission (was) granted to copy and/or print this le as long as the copyright notice and this permission is included on all copies. This le is also available as one book in Swedish and one in Russian. A complete textbook in Swedish on Fortran 90 has been prepared, and its translation into English is in progress.
13
16.1.9.1 Vector and matrix multiplication dot product(a, b)
length)
Computes the scalar product of two vectors (which should have the same
Computes the matrix product of two matrices which must have consistent ranks (such as (m,l) and (l,n)
matmul(a,b)
2 National Supercomputer Centre, University of Linkoping, S-581 83 L, Sweden. 3 Institute of Computational Technologies, Prospekt Lavrentyeva 6, Russian Academy
Division, SU-630090 Novosibirsk 90, Russia.
Victor E. Saouma
of Sciences, Siberian
Computing Literacy for Undergraduate Engineering Students
Draft
16.1 Background
16{5
16.1.9.2 Array Functions Returns a logical value that indicates whether all relations in mask are true, along only the desired dimension if the second argument is given. any(mask, dim) Returns a logical value that indicates whether any relation in mask is true, along only the desired dimension if the second argument is given. count(mask, dim) Returns a numerical value that is the number of relations in mask who are true, along only the desired dimension if the second argument is given. maxval(array, dim, mask) Returns the largest value in the array array, of those that obey the relation in the third argument mask if that one is given, along only the desired dimension if the second argument dim is given. minval(array, dim, mask) Returns the smallest value in the array array, of those that obey the relation in the third argument mask if that one is given, along only the desired dimension if the second argument dim is given. product(array, dim, mask) Returns the product of all the elements in the array array, of those that obey the relation in the third argument mask if that one is given, along only the desired dimension if the second argument dim is given. sum (array, dim, mask) Returns the sum of all the elements in the array array, of those that obey the relation in the third argument mask if that one is given, along only the desired dimension if the second argument dim is given.
all(mask, dim)
16.1.9.3 Array Inquiry Logical function which indicates if the array is allocated. lbound(array, dim) Function which returns the lower dimension limit for the array. if dim (dimension) is not given as an argument, we get an integer vector, if dim is included, we get the integer value with exactly that lower dimension limit, for which we asked. shape(source) Function which returns the shape of an array source as an integer vector. size(array, dim) Function which returns the number of elements in an array array, if dim is not given, and the number of elements in the relevant dimension if dim is included. ubound(array, dim) Function similar to lbound which returns the upper dimensional limits.
allocated(array)
16.1.9.4 Array Construction merge(tsource, fsource, mask) Function which joins two arrays. It gives the elements in tsource if the condition in mask is true and fsource if the condition in mask is false.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
16{6
WEEK 2: ARRAYS The two elds tsource and fsource have to be of the same type and the same shape. The result is also of this type and this shape. Also mask must have the same shape. Following is a rather complete example of the use of merge which also uses reshape from the next section in order to build suitable test matrices. Note that the two subroutines write array and write l array are test routines to write matrices which in the rst case are of a real type, in the second case of a logical type. implicit none interface ! This shall be explained nex week subroutine write_array (a) real :: a(:,:) end subroutine write_array subroutine write_l_array (a) logical :: a(:,:) end subroutine write_l_array end interface real, dimension(2,3) :: tsource, fsource, result logical, dimension(2,3) :: mask tsource = reshape( (/ 11, 21, 12, 22, 13, 23 /), & (/ 2, 3 /) ) fsource = reshape( (/ -11, -21, -12, -22, -13, -23 /), & (/ 2,3 /) ) mask = reshape( (/ .true., .false., .false., .true.,& .false., .false. /), (/ 2,3 /) ) result = merge(tsource, fsource, mask) call write_array(tsource) call write_array(fsource) call write_array(mask) call write_array(result) end subroutine write_array (a) real :: a(:,:) do i = lbound(a,1), ubound(a,1) write(*,*) (a(i, j), j = lbound(a,2), ubound(a,2) ) end do return end subroutine write_array
subroutine write_l_array (a) logical :: a(:,:) do i = lbound(a,1), ubound(a,1) write(*,"(8l12)") (a(i, j), j= lbound(a,2), ubound(a,2)) end do return end subroutine write_l_array
The following output is obtained Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
16.1 Background 11.0000000 21.0000000
16{7 12.0000000 22.0000000
13.0000000 23.0000000
-11.0000000 -12.0000000 -21.0000000 -22.0000000
-13.0000000 -23.0000000
t f 11.0000000 -21.0000000
f t
f f
-12.0000000 22.0000000
-13.0000000 -23.0000000
pack(array, mask, vector) Packs an array to a vector with the control of mask. The shape of the logical array mask has to agree with the one for array or mask must be a scalar. If vector is included, it has to be an array of rank 1 (i.e. a vector) with at least as many elements as those that are true in mask and have the same type as array. If mask is a scalar with the value true then vector instead must have the same number of elements as array.
The result is a vector with as many elements as those in array that obey the conditions if vector is not included (i.e. all elements if MASK is a scalar with value true). In the other case the number of elements of the result will be as many as in vector. The values will be the approved ones, i.e. the values which ful l the condition, and will be in the ordinary Fortran order. If vector is included and the number of its elements exceeds the number of approved values, the lacking values required for the result are taken from the corresponding locations in vector. The following example is based on the modi cation of the one for merge, but only the results are given array 11.0000000 21.0000000
12.0000000 22.0000000
13.0000000 23.0000000
vector -11.0000000 -21.0000000 -12.0000000 -22.0000000 -13.0000000 -23.0000000
mask t f
f t
f f
pack(array, mask) 11.0000000 22.0000000
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
16{8
WEEK 2: ARRAYS pack(array, mask, vector) 11.0000000 22.0000000 -12.0000000 -22.0000000 -13.0000000 -23.0000000
Returns an array of the same type as the argument source with the rank increased by one. The parameters dim and ncopies are integer. If ncopies is negative the value zero is used instead. If source is a scalar, then spread becomes a vector with ncopies elements that all have the same value as source. The parameter dim indicates which index is to be extended. it has to be within the range 1 and 1+(rank of source), if source is a scalar then dim has to be one. The parameter ncopies is the number of elements in the new dimensions. unpack(vector, mask, array) Scatters a vector to an array under control of mask. the shape of the logical array mask has to agree with the one for array. The array vector has to have the rank 1 (i.e. it is a vector) with at least as many elements as those that are true in mask, and also has to have the same type as array. If array is given as a scalar then it is considered to be an array with the same shape as mask and the same scalar elements everywhere. The result will be an array with the same shape as mask and the same type as vector. The values will be those from vector that are accepted (i.e. those ful lling the condition in mask), taken in the ordinary fortran order, while in the remaining positions in array the old values are kept.
spread(source, dim, ncopies)
16.1.9.5 Array reshape
Constructs an array with a speci ed shape shape starting from the elements in a given array source. If PAD is not included then the size of source has to be at least product (shape). If pad is included it has to have the same type as source. If order is included, it has to be an integer array with the same shape as shape and the values must be a permutation of (1,2,3,...,N), where N is the number of elements in shape, it has to be less than, or equal to 7. The result has of course a shape shape and the elements are those in source, possibly complemented with pad. The dierent dimensions have been permuted at the assignment of the elements if order was included, but without in uencing the shape of the result.
reshape(source, shape, pad, order)
! program to test the optional arguments to reshape interface subroutine write_matrix(a) real, dimension(:,:) :: a end subroutine write_matrix
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
16.1 Background
16{9
end interface real, dimension (1:9) :: b = (/ 11, 12, 13, 14, 15, 16, 17, 18, 19 /) real, dimension (1:3, 1:3) :: c, d, e real, dimension (1:4, 1:4) :: f, g, h integer, dimension (1:2) :: order1 = (/ 1, 2 /) integer, dimension (1:2) :: order2 = (/ 2, 1 /) real, dimension (1:16) :: pad1 = (/ -1, -2, -3, -4, -5, -6, -7, -8, & & -9, -10, -11, -12, -13, -14, -15, -16 /) c = reshape( b, (/ 3, 3 /) ) call write_matrix(c) d = reshape( b, (/ 3, 3 /), order = order1) call write_matrix(d) e = reshape( b, (/ 3, 3 /), order = order2) call write_matrix(e) f = reshape( b, (/ 4, 4 /), pad = pad1) call write_matrix(f) g = reshape( b, (/ 4, 4 /), pad = pad1, order = order1) call write_matrix(g) h = reshape( b, (/ 4, 4 /), pad = pad1, order = order2) call write_matrix(h) end subroutine write_matrix(a) real, dimension(:,:) :: a write(*,*) do i = lbound(a,1), ubound(a,1) write(*,*) (a(i,j), j = lbound(a,2), ubound(a,2)) end do end subroutine write_matrix
The output from the above program is as follows. 11.0000000 12.0000000 13.0000000
14.0000000 15.0000000 16.0000000
17.0000000 18.0000000 19.0000000
11.0000000 12.0000000 13.0000000
14.0000000 15.0000000 16.0000000
17.0000000 18.0000000 19.0000000
11.0000000 14.0000000 17.0000000
12.0000000 15.0000000 18.0000000
13.0000000 16.0000000 19.0000000
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
16{10
WEEK 2: ARRAYS 11.0000000 12.0000000 13.0000000 14.0000000
15.0000000 16.0000000 17.0000000 18.0000000
19.0000000 -1.0000000 -2.0000000 -3.0000000
-4.0000000 -5.0000000 -6.0000000 -7.0000000
11.0000000 12.0000000 13.0000000 14.0000000
15.0000000 16.0000000 17.0000000 18.0000000
19.0000000 -1.0000000 -2.0000000 -3.0000000
-4.0000000 -5.0000000 -6.0000000 -7.0000000
11.0000000 15.0000000 19.0000000 -4.0000000
12.0000000 16.0000000 -1.0000000 -5.0000000
13.0000000 17.0000000 -2.0000000 -6.0000000
14.0000000 18.0000000 -3.0000000 -7.0000000
16.1.9.6 ARRAY manipulation The shift functions return the shape of an array unchanged, but move the elements. cshift(array, shift, dim) Performs circular shift by shift positions to the left if shift is positive and to the right if it is negative. If array is a vector the shift is being done in a natural way, if it is an array of a higher rank then the shift is in all sections along the dimension dim. If dim is missing it is considered to be 1, in other cases it has to be a scalar integer number between 1 and n (where n equals the rank of array). The argument shift is a scalar integer or an integer array of rank n-1 and the same shape as the array, except along the dimension dim (which is removed because of the lower rank). Dierent sections can therefore be shifted in various directions and with various numbers of positions. eoshift(array, shift, boundary, dim) Performs shift to the left if shift is positive and to the right if it is negative. Instead of the elements shifted out new elements are taken from boundary. If array is a vector the shift is being done in a natural way, if it is an array of a higher rank, the shift on all sections is along the dimension dim. If dim is missing, it is considered to be 1, in other cases it has to have a scalar integer value between 1 and n (where n equals the rank of array). The argument shift is a scalar integer if array has rank 1, in the other case it can be a scalar integer or an integer array of rank n-1 and with the same shape as the array array except along the dimension dim (which is removed because of the lower rank). The corresponding applies to boundary which has to have the same type as the array. If the parameter boundary is missing we have the choice of values zero, .false. or blank being used, depending on the data type. Dierent sections can thus be shifted in various directions and with various numbers of positions. A simple example of the above two functions for the vector case follows, both the program and the output.
14
real, dimension(1:6)
Victor E. Saouma
:: a = (/ 11.0, 12.0, 13.0, 14.0, &
Computing Literacy for Undergraduate Engineering Students
Draft
16.1 Background
16{11 15.0, 16.0 /)
real, dimension(1:6) :: x, y write(*,10) a x = cshift ( a, shift = 2) write(*,10) x y = cshift (a, shift = -2) write(*,10) y x = eoshift ( a, shift = 2) write(*,10) x y = eoshift ( a, shift = -2) write(*,10) y 10 format(1x,6f6.1) end 11.0 13.0 15.0 13.0 0.0
12.0 14.0 16.0 14.0 0.0
13.0 15.0 11.0 15.0 11.0
14.0 16.0 12.0 16.0 12.0
15.0 11.0 13.0 0.0 13.0
16.0 12.0 14.0 0.0 14.0
Another example b = (/ 11.0, 12.0, 13.0, 14.0, 15.0, 16.0 /) 11.0 14.0 17.0
12.0 15.0 18.0
13.0 16.0 19.0
z = reshape( b, (/3,3/) )
17.0 11.0 14.0
18.0 12.0 15.0
19.0 13.0 16.0
x = cshift (z, shift = 2)
13.0 16.0 19.0
11.0 14.0 17.0
12.0 15.0 18.0
x = cshift ( z, shift = 2, dim = 2)
14.0 17.0 11.0
15.0 18.0 12.0
16.0 19.0 13.0
x = cshift (z, shift = -2)
17.0 0.0 0.0
18.0 0.0 0.0
19.0 0.0 0.0
x = eoshift ( z, shift = 2)
13.0 16.0 19.0
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 11.0
0.0 0.0 12.0
0.0 0.0 13.0
Victor E. Saouma
x = eoshift ( z, shift = 2, dim = 2)
x = eoshift ( z, shift = -2)
Computing Literacy for Undergraduate Engineering Students
Draft
16{12
WEEK 2: ARRAYS
Transposes a matrix, which is an array of rank 2. It replaces the rows and columns in the matrix.
transpose (matrix)
16.1.9.7 Array location Returns the position of the greatest element in the array array, if mask is included only for those which ful l the conditions in mask. The result is an integer vector! minloc(array, mask) Returns the position of the smallest element in the array array, if mask is included only for those which ful l the conditions in mask. The result is an integer vector! Note that the two subroutines write array and write l array are test routines to write matrices which in the rst case are of a real type, in the second case of a logical type.
maxloc(array, mask)
16.2 Assignment
16.2.1 Structural Design 16.2.1.1 Theory
The design of a steel truss entail the following steps: 1. Structural analysis in which the equations of equilibrium are applied at each node and written in terems of the unknown internal element forces and known externally applied load. This will result in a system of linear equations of the form [B] fxg = fPg
(16.1)
where fPg is the vector of externally applied load, and fxg the vector of unknown element forces (tension if positive, compression if negative). Note that the unknown vector contains both element forces ass well as reactions. 2. Analysis is performed for dierent loads, and then multiple load cases are coonsidered. Each load case is typically a linear combination of the basic load investigated. 3. Results (internal forces) are tabulated for all load cases, maximum forces determined, and each element is separately designed.
16.2.1.2 Assignment
The truss shown in Fig. 16.1 is to be designed. The statics [B ] matrix can be assembled4 The resulting statics matrix can be copied from 4 Note
that in assembling the matrix, each column corresponds to an unknown internal element force, or an external reaction. Each row corresponds to an equation of equilibrium.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
16{13
Draft
16.2 Assignment
Figure 16.1: Steel Truss
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
16{14
WEEK 2: ARRAYS
ftp/pub/Structures/cven4837/b-truss.dat and its inverse from ftp/pub/Structures/cven4837/b-truss-inv.dat
The three load vectors (corresponding to roof, snow, and live loads) are:
r=-[0., 0., 0., -0.9, 0., 0., 0., -1.74, 0., 0., 0., -1.68, 0., 0., 0., -1.68, 0., 0., 0., -1.68, 0., 0., 0., -0.84] s=-[0., 0., 0., -2.57, 0., 0., 0., -4.97, 0., 0., 0., -4.8, 0., 0., 0., -4.8 , 0., 0., 0., -4.8 , 0., 0., 0., -2.4] l=-[0., 0., 0., 0., 0., 0., 0., 0., 0., -6.4, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,-6.15, 0., 0.]
and are stored in
ftp/pub/Structures/cven4837/truss-load.dat
Write a Fortran-90 program which will 1. Read the [B] matrix and it inverse. 2. Check that the product of those two matrices is the identity matrix. 3. Solve for the roof, snow, and live load forces 4. Obtain the forces for each of the 3 following three load combinations Load Case Roof Live Snow 1 1.4 0 0 2 1.2 1.6 0.5 3 1.2 0.5 1.6 5. Determine the maximum load for each member 6. Select the cross sectional area of each member using allowable = 20 kips/in2 in compression and nal area of each member using allowable = 24 kips/in2 in tension. 7. Tabulate the results as shown in Table 16.1 plus an additional column showing the crosssectional area in in2. Note that Note that the actual results are given by Table 16.1.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
16{15
Draft
16.2 Assignment
Member 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
L0 ; L1 U0 ; L0 U0 ; L1 U0 ; U1 U1 ; L1 L1 ; L2 U1 ; L2 U1 ; U2 U2 ; L2 L2 ; L3 U2 ; L3 U2 ; U3 U3 ; L3 L3 ; L4 U3 ; L4 U3 ; U4 U4 ; L4 L4 ; L5 U4 ; L5 U4 ; U5 U5 ; L5
Load Load Cases Design Load Roof Snow Live 1 2 3 Compr. Tens. 0. 0. 0. 0. 0. 0. 0 0 -8.5 -24. -13. -12. -35. -55. -55. 0 12. 34. 20. 17. 52. 79. 0 79. -9.8 -28. -16. -14. -43. -65. -65. 0 -6.8 -20. -11. -9.6 -30. -45. -45. 0 9.8 28. 16. 14. 43. 65. 0. 65. 7.3 21. 16. 10. 38. 50. 0. 50. -15. -44. -29. -22. -72. -100. -100. 0 -4.6 -13. -3.9 -6.5 -14. -29. -29. 0 15. 44. 29. 22. 72. 100. 0 100. 4. 11. 5.2 5.6 15. 26. 0 26. -18. -52. -32. -26. -83. -120. -120. 0 -2.7 -7.8 -3.6 -3.8 -10. -18. -18. 0 18. 52. 32. 26. 83. 120. 0 120. 1.4 3.9 4.6 1.9 9.8 10. 0 10. -19. -55. -36. -27. -90. -130. -130. 0 -0.97 -2.8 -3.3 -1.4 -6.9 -7.3 -7.3 0 19. 55. 36. 27. 90. 130. 0 130. -0.89 -2.5 4.2 -1.2 5.1 -3.1 -3.1 5.1 -19. -53. -38. -26. -93. -130. -130. 0 0.66 1.9 3.1 0.92 6. 5.3 0 6. Table 16.1: Result of Truss Design
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
WEEK 2: ARRAYS
Draft
16{16
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
Chapter 17
WEEK III; PROGRAM UNITS; POINTERS 17.1 Background
17.1.1 Program Units A fortran 90 code is a modular hierarchical object de ned by fundamental blocks. 2 Each program unit may have one or more external procedures. Those procedures (function and/or subroutine) are nearly independent pieces segments of the code. They can be written separately, make it easier to debugg the code, can be reused in other programs, and can be reused in the same code. 3 Program and procedure can share data through the module unit.
1
17.1.1.1 Main Program Always assign a header, i.e. program stress. 5 End the program similarly: i.e. end program stress. 6 Always return control to the main program upon termination (good programming practice), and hence there should be no more than one stop statement in your code. 7 For abnormal completion, you may append a character string after the stop 4
stop 'Incomplete data, abnormal completion'
8 There should be few executable statements in the main program. Calls to subroutines should be used instead.
Draft
17{2
WEEK III; PROGRAM UNITS; POINTERS
17.1.1.2 Functions Often times an application program needs to have a relatively simple operation to be performed. If that operation is to be repeated, and returns a single variable as a result of an operation on one or more variables then we should use the function procedure which has the general form
9
function-type
function
function name(argument list)
the function must also end with a return and endfunction-name statements. 10 The function arguments referenced in the main program are the actual arguments. They should match in type, number and order the dummy ones in the function statement. 11 Functions can be de ned within a subroutine if necessary. 12 If one of the function arguments is an array, its dimensions must be speci ed in both the main program and the function. 13 A function may call other functions. 14 Because a function returns a single value, the function name should appear in the type statement in the main program. 15 The intent of the use of each variable should be de ned according to whether it is only to be used as an input variable (in), output variable (out), or both (inout): 16 Following is a main program program statistic ! declare variables implicit none real :: average real allocatable :: fc(:) integer :: error, k, n ! open the data file and read number of data points open(unit=1,file='strength.dat') read(1,*) n ! allocate space for array x allocate(fc(n), stat = error) if (error .ne. 0) then print*, "Allocation failed" stop endif ! read the data points read(1,*)(fc(i),i=1,n) ! print the average (which is to be determined from a separate function) print*, average(fc,n) ! end program statistic
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
17.1 Background
17{3
which references the following function real function average(x,n) ! This function determines the average value of an array x ! variable declaration implicit none integer :: i, n real :: x(n), sum=0.0 intent(in) :: x,n ! Note the intent declaration as in do i=1,n ! Note that we could have used the intrinsic function sum sum=sum+x(i) ! instead of this loop end do average=sum/real(n) return end function average
17.1.1.3 Recursive Subprograms 17 Fortran 90 supports recursion. If a subprogram calls itself, directly or indirectly, the keyword recursive must appear in the subprogram statement.
Recursive functions must also declare a result variable to avoid ambiguity with array-valued functions that are directly recursive. The result variable is used to hold the function result for each function invocation; the function name is used to invoke the function itself. Consequently, the recursive function's name should never appear on the left side of an assignment statement. An example of a recursive factorial function is shown below.
18
recursive function factorial( n ) result( f ) integer f integer, intent( in ) :: n if ( n <= 0 ) then f = 1 else f = n * factorial( n-1 ) end if end function factorial
17.1.1.4 Subroutines Subroutines are procedures used to perform operations which are too complex to be performed by functions (if several values need to be returned, or values are simply to be read and passed back). 20 Just as we have intrinsic functions, fortran 90 has intrinsic subroutines which are included in the compiler. You should consult your compiler manual to determine which intrinsic subroutines are pre-de ned. 21 The general format to reference a subroutine is through the following executable statement
19
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
17{4
WEEK III; PROGRAM UNITS; POINTERS call
22
subroutine-name (argument list)
In turn, the rst line in a subroutine should look like subroutine
subroutine-name(argument list)
Contrarily to functions, a subroutine use the argument list to identify both input and output values to a subroutine. 24 A subroutine may return zero, one or many values. 25 Declaration of all parameters should include the intent attribute. 26 The subroutine should include a return and end subroutine 27 It is advisable to have input arguments preceding output ones. 28 Following is a main program 23
program statistic ! declare variables implicit none real :: average, fc_min, fc_max real allocatable :: fc(:) integer :: error, k, n ! open the data file and read number of data points open(unit=1,file='strength.dat') read(1,*) n ! allocate space for array fc allocate(fc(n), stat = error) if (error .ne. 0) then print*, "Allocation failed" stop endif ! read the data points read(1,*)(fc(i),i=1,n) ! call the subroutine which will compute the average, minimum and maximum values call stat(fc, n & average, fc_min, fc_max) ! print results print*, "Average compressive strength ',average print*, "Minimum compressive strength ',fc_min print*, "Maximum compressive strength ',fc_max end program statistic
which references the following subroutine subroutine stat(x, n & average, x_min, x_max) ! This subroutine determines the average minimum and maximum value of an array x ! variable declaration
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
17.1 Background
17{5
implicit none integer :: i, n real :: x(n), x_min=x(1), x_max=x(1), average, sum=0.0 intent(in) :: x,n intent(out) :: average, xmin, xmax ! do i=2,n sum=sum+x(i) if ( x(i) < x_min ) x_min = x(i) if ( x(i) > x_max ) x_max = x(i) end do average=sum/real(n) return end subroutine stat
17.1.1.5 yModules A module is a collection of declarations and subprograms. Each modules has two components: 1. The speci cation declares variable types, de nes derived types, and marks what is visible or hidden from calling programs and subprogram interfaces 2. The subprogram part actually provides the code for subroutines and functions involved in a module. More about modules later.
29
17.1.1.6 y Interface An interface speci cation should be de ned at the beginning of the main program so the compiler will know exactly how best to treat each argument of a subroutine or function. To use a subroutine de ned as above, the following would need to be placed at the beginning of the main program: More about modules later.
30
17.1.2 Derived Data Type There are two types of data types in fortran Intrinsic such as integer, real, double-precision, logical, complex and character. An array de ned through an intrinsic data type can be of only one type, i.e. we can not mix two types in the same array. Derived or user de ned data types (similar to records or structures in other languages) are available in Fortran 90. 31
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
17{6
WEEK III; PROGRAM UNITS; POINTERS
In a derived data type we can group dierent data types together. 33 To assign values to the component of a derived data type, we use the structure identi er followed by a percent sign (%) followed by the component identi er. 34 The following example should be self-explanatory. 32
! define element data type type element_type character*10 :: type real :: length, area, young integer :: first_node, second_node end type element-type ! type (element_type) :: element(100) do i=1,100 read(5,*)element(i)%type, element(i)%first_node, element(i)%second_node, & element(i)%length, element(i)%area, element(i)%young end do
17.1.3 Pointers
17.1.3.1 Pointer Variable 35 A pointer target
variable, called pointer is a mere alias to another variable which is called the
real, pointer :: pntr real, target :: x=10., y=20., z
So far we have not yet speci ed what they are.
17.1.3.2 Pointer Assignment 36
To assign a value to a pointer we use the operator specifed by =>
pntr=>x z=pntr
will result in pntr=10 and z=10 37 A pointer can be nulli ed nullify(pntr}
A pointer can point to other pointers, and hence to their targets, or to a static object that has the target attribute: 39 There is also an internal function associated in order to investigate if a pointer is associated (and if it is associated with a certain target) and a statement nullify in order to terminate the association.
38
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
17.1 Background
17{7
if ( associated (a) ) write(*,*) ' a is associated ' if ( associated (a, b) ) write(*,*) ' a is associated with b ' nullify (a)
40
Yet another example
real, target real, pointer a = 10. p => a q => p a = 2.
:: a :: p, q
Here the value of q equals 2. since both p and q point towards the same variable a and that one has just changed its value from 10. to 2. We now make a simple variation. real, target :: a, b real, pointer :: p, q a = 10. b = 2. p => a q => b
Now both the values of a and p are equal to 10. and the values of both b and tt q are 2. If we now give the statement q=p, all four variables will get the value 10., which means that an ordinary assignment of pointer variables has the same eect as the conventional assignment b=a. If we instead give a pointer association q=>p, then the three variables a, p and q all have the value 10. while b contains the value 2. In the second case q only points to the same variable as p while in the rst case q becomes the same as p, and the value addressed by q becomes equal to the value addressed by p. 41 Important application of pointers are lists and trees, and especially dynamic arrays. 42 Note that a pointer has both type and rank, and that these must agree with the corresponding target. This increases the security at the use of pointers, it is therefore not possible by mistake to let a pointer change values of variables of other (dierent) data types. The fact that you have to specify that a variable can be a target also increases both security and eciency of the compilation. real, real, a => c =>
target pointer b(4,:) b(:,4)
:: b(10,10) :: a(:), c(:) ! vector a becomes the fourth row ! and vector c becomes the fourth ! column of the matrix b
or real, target :: matrix(100,100) real, pointer :: window(:,:) integer :: n1, n2, m1, m2 window => matrix(n1:m1, n2:m2)
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
17{8
WEEK III; PROGRAM UNITS; POINTERS
If you later wish to change a dimension of the partial matrix window you only need to make a new pointer association. Please note that the indices in window are not from n1 to m1 and from n2 to m2 but from 1 to m1-n1+1 and from 1 to m2-n2+1.
17.1.3.3 Dynamic Memory Allocation for Pointers 43
Pointers can also be assigned using allocate
(pointer)
which will assign a target memory location to the pointer. integer, target :: x integer, pointer :: ptr_1, ptr_2 ... ptr_1=>x allocate(ptr_2)
17.1.3.4 Pointers to Arrays There does not exist arrays of pointers directly in Fortran 90, but you can construct such facilities by creating a new data type.
44
! declare the derived data type as pointer type pointer_element real pointer :: ptr end type pointer_element ! ! declare variables implicit none integer :: i real, target, dimension(5) :: load=(/10., -20., 15., 25, -32./) type(pointer_element) :: y(5) ! do i=1,5 y(i)%ptr=>load(i) end do
Yet another example which stores a lower (or left) triangular matrix with rows with varying length.
45
! define a new data type row type row real, pointer :: r(:) end type ! specify the lower triangular matrices l as vector ! of rows with varying length integer :: n type(row) :: l(n) ! allocate the matrix
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
17.1 Background do i = 1, n allocate (l(i)%r(1:i)) end do
17{9 ! various length of rows
Finally, pointers allow the creation of a new type of data structure linked data structures. This is similar to an array because it is a group of nodes that contain information and have an order (i.e. there is a rst, second order and so on). However, a linked list diers from the array in that we do not use a subscript to reference a node in the linked list, instead we use a pointer variable. 47 The linked list is built by associating pointers to the nodes on the linked list as the need arises, and we do not have to declare the maximum size of the linked list. Each node in the linked list has a pointer contained within it that points to the next node in the list.
46
17.1.3.5 Pointers as a Tool for Linked Lists 48 Pointers may be used with scalar or array quantities of any type and are used to construct dynamic structures such as linked lists and trees. 49 The following program illustrates how a dynamic data structure can be declared and manipulated. program LinkedList type node real data type( node ), pointer :: next end type node type( node ), pointer :: list, current nullify( list )
! Initialize list to point to no target.
! Place two elements in the list. allocate( list ) ! call random_number( list%data ) ! allocate( list%next ) ! call random_number( list%next%data ) ! nullify( list%next%next ) ! ! Output the list. current => list do while ( associated( current ) ) print *, current%data current => current%next end do end program LinkedList
Victor E. Saouma
Reserve space for first node. Initialize data portion. Reserve space for second node. Initialize data portion. Initialize next to point to no target.
! Assign target of list to target of current.
Computing Literacy for Undergraduate Engineering Students
Draft
17{10
WEEK III; PROGRAM UNITS; POINTERS
17.2 Assignment 17.3 Mendeleev The Mendeleev table contains 106 known elements. Each element is characterized by name character of length 12 symbol character of length 2 atomic number which is an integer mass a double precision number number isotopes an integer indicating the total number of isotopes for the current element weight which is a list of number isotopes double precision number. A sample (input) data le would read as: Hydrogen 1.007825 Helium 3.016030 .....
H 1 1.00794 3 2.014000 3.016050 He 2 4.00260 5 4.002600 5.012220 6.018886
8.033920
Write a program isoweight which will 1. Open a data le mendelev.dat containing all the pertinent data 2. create a derived data type mendeleev in which weight is an allocatable array and pointer 3. Loop over all the elements, and for each one (a) Read name, symbol, atomic number, mass, and number of isotopes (b) Allocate sucient memory for each isotopic weight (based on the number of isotopes read). (c) Read the individual weight into the allocated memory 4. Print the results in the following format 0 1 2 3 4 5 6 123456789012345678901234567890123456789012345678901234567890 Name Symbol Number Mass Isotope Weights -------------------------------------------------------------Hydrogen H 1 1.00794 1 1.007825 2 2.014000 3 3.016050 Helium
Victor E. Saouma
He
2
4.00260
1
3.016030
Computing Literacy for Undergraduate Engineering Students
Draft
17.4 Linked List
17{11 2 3 4 5
4.002600 5.012220 6.018886 8.033920
...
17.4 Linked List 1. Write a subroutine named new order that is referenced with the following statement call new order(order,item,first,last)
the subroutine should add a node at the end of the list containing the integer order number and the integer item number 2. Write a subroutine named print orders that is referenced as call print orders(first)
this shubroutine should print all the information in the orders linked list. If the list is empty, print an appropriate message. 3. Write a subroutine order filled that is referenced as call order filled(first,order)
whish should delete the node in the linked list that corresponds to the order number. If the correspondingentry is not in the linked list, print an error message. Write a program which uses all three above subroutines to accept information from the keyboard, either to add data to the end of the linked list, or to remove data from the linked list. Assume that the terminal interaction begins with this message: Enter N to add new order to list D to delete order from list Q to quit program
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
WEEK III; PROGRAM UNITS; POINTERS
Draft
17{12
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
Chapter 18
WEEK 4: MAKE, DEBUGGER 18.1 Debugging options Sometimes there are mysterious things going on within our programs. The code looks like it should execute properly, but for some reason the code bombs, or produces questionable results. These \reasons" are called \bugs". The FORTRAN compiler has a few options to help in tracking these bugs down, or debugging you code. These options are extremely helpful for debugging code under development, but they should not be used for production programs. The extra code and expanded symbol table that these options generate will increase run time. Also available is a more extensive debugging tool called Debugger, see section 18.4. The following options can be given to create information need for debugging and pro ling tools. Note that these options must be given both in the compile and link steps if you compile and link separately. -C Generates additional code for run-time array bounds checking. When the program is executing , it will print a warning message to the screen if a reference to an array element occurs that falls outside of the arrays declared boundaries. -g Generates an expanded symbol table for the debugger. -p Compiles and links the program for pro ling with prof. A program compiled with the -p option will generate a le called mon.out when executed. This le contains program execution statistics. The pro ler prof will read this le and produce a table describing your program's execution. To pro le a program you need to compile each source le with the -p option, and also specify this option in the link step. An example: f77 -p -c file1.c f77 -p -c file2.c f77 -p file1.o file2.o
Now the program can be executed, and the le mon.out will be generated. The pro ler then be run to make the information in mon.out readable. Giving one of the commands:
Draft
18{2
WEEK 4: MAKE, DEBUGGER prof prof mon.out prof mon.out > prof.out
will run the pro ler. The last command will put the output in a le called prof.out, this le can then be viewed in an editor. -pg Compiles and links the program for pro ling with gprof. This option is the same as the -p option, except that the le generated is called gmon.out and it should be used with the program gprof.
18.2 FORTRAN Preprocessor There is a preprocessor that understands directives like #include to include les and #de ne to de ne symbolic constants. The f77 compiler will automatically run the preprocessor on all les with an .F extension (and not on les with an .f or .for extension). The #include directive is used to include another le in the text processed by the compiler. (This will not aect the original source le). If the line: #include "definitions.h"
is present in a source le, the preprocessor will replace the line with the contents of the le de nitions.h before continuing. The #de ne directive is used to de ne symbolic constants. If the line: #define PI 3.1415926
is present in a source le, all uses of the symbol PI after this line will be replaced with 3.1415926.
18.2.1 System Calls
As with most compilers, it is possible to make system commands from your Fortran program. The use of this feature can make a program very powerful when used to access other tools available on the system. Since the system calls are not standard among compilers and computer systems, they should be used cautiously if the program is to be at all portable. Usage: CALL SYSTEM(string) where string is an operating system command or program call. System calls are especially good for making programs more \user friendly". For example, many programs prompt for input le names. It would be convenient if a program provided a list of les in the current directory that have the correct extension. Following is a short Fortran routine that lists all les having the extension \.dat". C
PROGRAM PROMPT CHARACTER*40 FILENAME USE A SYSTEM CALL TO PROVIDE A LIST OF POSSIBLE INPUT FILES
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
18.3 Make C
1
18{3
CALL SYSTEM('ls *.dat') PROMPT USER FOR INPUT DATA FILE NAME WRITE(*,*)' ENTER THE INPUT DATA FILE NAME > ' READ(*,1) FILENAME FORMAT(A40)
18.3 Make When developing a program, the executable le must be continuously recreated as the source code is modi ed and recompiled. This can become a hassle, especially if your program is lengthy. If your modi cations have only been in a few of the subroutines making up your program, it is a considerable waste of time to recompile the entire program. This is where the make command is useful. A program can be created from several source les, each le containing one or more subroutines. Make will only recompile those les that have been modi ed since the last compile and will relink all the object les and create a new executable. To use make you need a description le that contains the information make needs to create your program. This information includes the names of the source les, the compiler you wish to use, the compiler options, and so on. This le is called the make le. While this section will not go into the million and one uses for make it will show you how to build a make le. Basically, a make le consists of a number of de nitions and a number of targets. The de nitions are used to specify le names, which compiler and linker to use, ags to use when compiling, etc. The targets is what tells make what to do when invoked. A target speci es a dependency and a list of command. The dependencies are used to tell make when to remake something, and the commands are used to tell make what to do to remake the target. In the following example, the target $(PROGRAM) is dependent on the les in $(OBJECTS), and the command to make the program from the object les is speci ed on the next line (note that the command lines must start with a tab character). Make is partially intelligent, it understands how to make an object le from a source le, for example a .o le from a .f le. Thus when it sees that $(PROGRAM) is dependent on a number of object (.o) les, it will nd the source (.f) les in the directory and create the .o les automatically. The following is an example of a simple make le. The lines starting with # are comments, the numbers in parentheses refers to the more detailed explanations following the example. # (1) Name of the program. PROGRAM = sample # (2) List of source files making up the program. SOURCES.f = \ file1.f \
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
18{4
WEEK 4: MAKE, DEBUGGER file2.f \ file3.f \ file4.f
# (3) Linker to use. LINK = $(LINK.f) # (4) Flags to the compiler and linker. FFLAGS += -g # (5)Source and object files. SOURCES = $(SOURCES.f) OBJECTS = $(SOURCES.f:%.f=%.o) # (6) Default target. all: $(PROGRAM) # (7) Program target. $(PROGRAM): $(OBJECTS) $(LINK) -o $(PROGRAM) $(OBJECTS) # (8) Clean target. clean: $(RM) $(OBJECTS) core # (9) Dependencies. file1.o: file1.inc file2.o: file1.inc file2.inc file3.o: file1.inc
The make le and the source les must reside in the same directory, and the object les and the executable le will be put in that directory. 1. Here the name of the program is speci ed. In our example, the program is called sample. 2. This section de nes the sources to be used in the program. In this example the source les are in FORTRAN, if they were in C, the extensions would all be .c. If there is more than one le, follow the lename with a backslash, hit return, then tab and type in the next lename, etc. 3. This section speci es the source language. Specify LINK.f for FORTRAN and LINK.c for C. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
18.3 Make
18{5
4. Specify the compiler ags, FFLAGS for FORTRAN, CFLAGS for C. Here the -g invokes the debugger, see section 18.4 for more information about this option. For more information on other compiler options see the respective section on the compiler you are interested in using. 5. We will now de ne SOURCES to contain all the source les listed in SOURCES.f. The $ means to use all that was de ned for SOURCES.f and de ne SOURCES. Next we will de ne OBJECTS, to contain all the object les. The % is considered a wildcard by make, so it will take all the .f les in SOURCES.f and create the corresponding .o les. 6. The default target is usually called all. If make is invoked without any arguments, the rst target is processed. Here the all target will just invoke the $(PROGRAM) target to make the program. 7. The $(PROGRAM) target is the target to create the executable le by linking all the object les and creating the executable with the name you have de ned in PROGRAM. 8. The clean target is used to clean up the directory of the program. Giving the command make clean will remove all the object les and the core le, if any. 9. The last section of the make le is to de ne any dependencies. For example if you have used an include le in your subroutines, the object le is dependent on both the source le and the include le. So, if either the source le or the include le has changed, you will want your object le updated. Once your make le is complete, the command to create your program is simply: > make
This looks for a le called make le in whatever directory you are in. If you want to call your description le something other than make le you would use the -f option as follows > make -f filename
To make another target than the default one, specify the target on the command line to make: > make target
Usual targets are all (usually default), the program name, both of which makes the executable le, and clean, with cleans up in the directory. If you need more information with creating your make le the on-line man pages may help. Also the book Managing Programs with make by Andrew Oram and Steve Talbott, O'Reilly and Associates, Inc. may prove very helpful. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
18{6
WEEK 4: MAKE, DEBUGGER
18.4 Debugger Written by Johannes Hermanrud
18.5 Introduction to Debugging A debugger is a program that makes it easy to debug programs. Using a debugger, one can: run the program in a normal fashion, step through the program line by line, run the program, but stop the execution at speci ed places (by setting breakpoints), continue execution after a stop, see the contents of variables, either at speci ed times or continuously, and see the call stack, i.e. see which functions has been called to reach the current point of execution. This information is valuable in deciding which parts of the program are actually executed, and what the values of the program's variables are at dierent points during the execution. When a program has a serious error, such as a segmentation fault, the operation system will create a le called core in the current working directory. This le can be used with a debugger to nd out where in the program the error occurred. See the command where for details.
18.5.1 The debugger
Debugger is a tool that can be used with C, FORTIN, Pascal, Modula-2 and assembler (See section 18.5.2 for how to run the debugger). Debugger opens a window on the screen containing a menu bar and ve subwindows.
Menu Bar There are ve menu options each with their corresponding submenus. Each menu and submenu are brie y described below:
the Program menu allows the users to debug a new program, go to a speci c line or
function in the current program, edit the source code for the current program using the vi editor, compile the source with or without command line arguments and list all of the program modules. the Breakpoint menu makes it possible for the programmer to place a breakpoint anywhere in the program so that the execution will stop at a certain point. Any breakpoints which have been set may also be removed through this menu. the Execution menu contains many of the same commands that are present in the Command Subwindow which allow you to step through the program or to run the program until completion. Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
18.5 Introduction to Debugging
18{7
the Stack menu displays which function the execution is in and at which line. This menu will also allow the programmer to go up or down one call level. the Data menu contains options to allow one to display the value of variables and to evaluate variables. the Props menu is a way in which the default properties of the debugger may be changed.
>From top to bottom the subwindows are (refer to gure 18.1). Status Subwindow. This area displays information about the state of the debug session. The following information is given: the name of the le currently displayed in the source subwindow, the name the function the debugger last stopped in, the number of the line last stopped at, the numbers of the rst and last lines displayed in the source subwindow. This information is updated when a command has been executed and when the window is resized. Source Subwindow. This text subwindow displays the source les of the program currently being debugged. The program is initially loaded by using the debug command in the command subwindow. The source le containing the main program code will appear in this window. The text can be scrolled using the scrollbar. The le to be displayed can also be selected using the le command. Also, the func command can be used to display the le containing a speci ed function. The line at which the execution of the program is stopped is marked by an arrow. Breakpoints are marked by a stop sign. Buttons Subwindow. This area contains buttons that can be selected to perform a number of commands. Many of the commands require associated arguments such as line numbers, function or subroutine names, etc. These arguments can be de ned by marking the lines or function names with the mouse in the source window. Marking is performed with the left and middle mouse buttons (same as with the text editor) and is done prior to selecting the function button. Command Subwindow. Debugger reads commands from this area and the program output that is directed to the standard output device (screen prompts, etc.) is displayed here. The text can be scrolled using the scollbar. To type commands in this subwindow, rst activate the text cursor by placing the mouse cursor in the window and pressing the left button on the mouse. Display Subwindow. This area shows the values of variables speci ed with the display command. The text can be scrolled using the scollbar. The display command needs to be used only once for a single variable, as the display of the variable will be updated Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
18{8
WEEK 4: MAKE, DEBUGGER throughout the execution of the program. To get the display window to pop-up either type display variable name or select "Display Window..." from the data menu.
Figure 18.1: Debugging Tool
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
18.5 Introduction to Debugging
18{9
18.5.2 Running the debugger
Debugger can be started using the Bechtel Lab menu from the programming tools submenu. When the debugger option is selected the debugger window will appear on the screen. The easiest way to load your program is to choose the le from the program loader menu which automatically appears when the debugger is called up. Keep in mind that the program name that you choose must be the name of an executable. At this point the source code of your program should appear in the window. The next step is to set stopping points within the program. Important Note: In order for debugger to work with your program, your program must have been compiled using the -g option. For example: % f77 -g -o bobs_program bobs_program.f
18.5.3 Debugger Commands
This section describes some of the most used debugger commands. These commands must be typed in in the command subwindow. Some commands are also available on a button, these are marked (button) in the following
debug le Debug the le le instead of the le currently being debugged. run [args] (button) Start execution of the current program using the arguments args. If no
arguments are given, the arguments of any previous runs are used. The execution will stop at any breakpoints set with the stop command. rerun [args] Start execution of the current program using the arguments args. If no arguments are given, the program is run without arguments. The execution will stop at any breakpoints set with the stop command. next [n] (button) Execute the next n source lines, counting a function call as a single statement. If n is not given, one line is executed. step (button) Execute the next n source lines, stepping into functions. If n is not given, one line is executed. cont (button) Continue execution from where it stopped. The execution will stop at any breakpoints set with the stop command. stop at n (button) Stop execution at line n if that line is reached during execution. The easiest way to set stopping points is to mark the line in the source sub-window using the mouse. Then click on the STOP button using the left mouse button. A \stop sign" will then appear in the source window. stop in function (button) Stop execution at the rst line in function function when that function is entered.
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
18{10
WEEK 4: MAKE, DEBUGGER
where List the functions that have been called to reach the current point of execution. When
debugging a program that has a core le, this command can be used when starting the debugging session to see where the core dump occurred. display variable Display the value of the variable variable in the display subwindow. This command only needs to be performed once for a single variable. When the variable changes value, the displayed value will re ect this. The Display* button will display a pointer. clear [n] Clear breakpoints on line n, if n is not given, clear the breakpoint last stopped at. change directory - cd path When the debugger is started from the menu system, the current directory is your home directory. Generally it is best to run the debugger in the directory in which your program resides, particularly if your program must read any data les. To change from your home directory to a subdirectory called homework/CVEN5555 type : (debugger) cd homework/CVEN5555
Victor E. Saouma
Computing Literacy for Undergraduate Engineering Students
Draft
Bibliography [1] A. Biran and M. Breiner. MATLAB for Engineers. Addisoon-Wesley, 1995. [2] D.M. Etter. Engineering Problem Solving with MATLAB. Prentice-Hall, 1993.