text
stringlengths
8
1.01M
About: Brief Trigonometry Tutorial Metadata Name: Brief Trigonometry Tutorial ID: m37435 Language: English (en) Summary: Many of the computational requirements for an introductory physics course involve trigonometry. This module provides a brief tutorial on trigonometry fundamentals that is designed to be accessible to blind students.
For the help you need to support your course Find resources by… About us mathcentre was developed by a group from the Universities of Loughborough, Leeds and Coventry, the Maths Stats and OR Network and the Educational Broadcasting Services Trust in 2003. Important components of the site were developed through the sister project mathtutor which was funded by the HEFCE and the Gatsby Charitable Foundation. mathcentre was upgraded in 2010 with funding from JISC. As part of this upgrade, mathcentre resources are being deposited in the JorumOpen and FETLAR repositories. mathcentre has been set up to deliver mathematics support materials, free of charge, to students, lecturers and everyone looking for post-16 maths help. The mathcentre team are a group of people who run university mathematics support centres, who teach mathematics, and who design new media products for learning. mathcentre gives you the opportunity to study important areas of pre-university mathematics, which you may have studied before or may be new to you - the maths you know you will need for your course. There are a variety of resources - self study guides; test yourself diagnostics and exercises; video tutorials; iPod and 3G mobile phone downloads; and case studies. Resources are available on-line, and may be printed or downloaded. The current mathcentre team NationalAudrey Jones Pink Mayhem Audrey Jones is a designer and developer for Pink Mayhem and has been responsible for the design and development of the upgrade of mathcentre. She has over twelve years experience of providing web and elearning services to both educational institutions and the private sector. Dr Aruna Palipana Loughborough University Aruna Palipana is the Learning Technology Manager at Loughborough University's Mathematics Education Centre since its establishment in 2002. Aruna's e-learning experience includes development and evaluation of educational software, web based distance learning and computer aided assessments. He was involved in e-learning projects such as HELM, EASEIT-Eng, BestMaths, ExPOUND and FETLAR. With a first degree and a PhD both in Mechanical Engineering and five years of experience as a university Lecturer in Mechanical Engineering, Aruna has a good understanding of the mathematical needs of the engineering undergraduate. Dr Janette Matthews Loughborough University Janette Matthews is the Project Pedagogic Officer in the Mathematics Education Centre at Loughborough Universityand has played a major role in the recent upgrade of mathcentre and the deposit of resources to OpenJorum and FETLAR. She is a Support Tutor in the Eureka Centre for Mathematical Confidence working with students with Specific Learning Differences and provides workshops for students preparing for Employers' Numeracy Tests. Moira Petrie SIGMA CETL Moira Petrie is Assistant Director of sigma - a Centre for Excellence in the Provision of University-wide Mathematics and Statistics Support - funded by HEFCE and run collaboratively by Loughborough and Coventry Universities. sigma is building on the extensive experience in the support of thousands of students from across these universities for whom mathematical and statistical methods are required components of their undergraduate and postgraduate programmes. All materials developed are made available through the mathcentre site. Moira has several years experience of working in industry, in a number of sectors, including e-learning, IT training and electronic media production. The legacy mathcentre team Shaun Canon EBS Trust Shaun managed the recent upgrading of mathtutor and co-managed the original production. He was responsible for the wider distribution of the resources outside the UK. Peter Coltman University of Leeds Peter Coltman has worked all his life in educational television, both in Britain and abroad, and mostly in higher education. He has won the Educational Television Association's premier award four times. In retirement, he now works with the Citizens Advice Bureau and is a trustee for the York Travellers Trust, Solace and The Joseph Rowntree Charitable Trust. Nick Blenkin SIGMA CETL Nick Blenkin was sigma's industrial placement student at Coventry for 2009/10. He has successfully completed the first two years of an undergraduate Mathematics and Computing degree at Coventry University. Nick was involved with the testing of the mathcentre website and the production of several tutorial videos.Janice Gardner EBS Trust Janice Gardner helped to develop, promote and publicise mathcentre and its sister project mathtutor. She was formerly EBS Trust Company Secretary and managed projects using new media for distance learning. She continues to maintain a keen interest in developments NationalPaul Newman Loughborough University Paul Newman joined Loughborough University in 2003, to design and develop the original mathcentre website and resource database. He now works for the Engineering Centre for Excellence in Teaching and Learning (engCETL), where he develops e-learning tools and applications. Tom Roper University of Leeds Tom Roper is Head of the School of Education at the University at Leeds and previous Head of Initial Teacher Training. He spent 17 years teaching mathematics in schools and colleges before moving into mathematics teacher training. As well as training teachers of mathematics, he teaches mathematics to first year undergraduate physicists. Dr David Saunders Symplekta David Saunders has extensive experience of distance education. For many years he was a BBC producer with the Open University, and has also taught maths at Worcester College, Oxford. For the past ten years he has combined mathematical research with activities as an educational software developer; he now plans to concentrate on research. Professor Mike Savage University of Leeds Mike's academic career spans 40+ years teaching mathematics and theoretical mechanics whilst researching in fluid dynamics. His contributions to work at the school/university transition include: 3. Newton's Mechanics: Who Needs It? (Co-author) @Findings and Recommendations of a two day seminar, Cambridge, 2008. Current interests concern the provision of effective mathematics and mechanics support for students entering physical science and engineering courses in higher education. Dr. Jim Stevenson EBS Trust We remember with thanks and great fondness the contribution of Dr Jim Stevenson who died February 2007. As Chief Executive of the Educational Broadcasting Services Trust and former BBC Open University Head of Programmes and Education Secretary, his understanding of distance learning through television and new media inspired and guided development of the mathtutor resource. Dr. Sarah Williamson SIGMA CETL Sarah Williamson is the eLearning Change Champion for Cardiff University. From August 2005 to May 2007 Sarah was the Assistant Director of sigma - a Centre for Excellence in the Provision of University-wide Mathematics and Statistics Support - funded by HEFCE and run collaboratively by Loughborough and Coventry Universities. Sarah has a PhD in Chemical Engineering and has previous experience of working in industry, teaching undergraduate engineering students, directing the LTSN MathsTEAM project and working for the Higher Education Academy - Engineering Subject Centre.
Monmouth Junction TrigonometryIn this way, graphing an inequality makes sense. Algebra 2 students are tasked with putting their previous knowledge to the test. This is where we first see conic sections, the unit circle, and roots of real and complex functions.
Courses MATH 010 - Finite Mathematics Much of the mathematics which impinges on everyday life is of the finite variety. This course will introduce students to topics from Number Theory, Combinatorics, Complexity Theory, Difference Equations, Game Theory, Geometry, Graph Theory, Information Theory, Group Theory, Logic, Probability and Simple Descriptive Statistics, and Set Theory. Prefer- ence will be given to topics which convey to the student the prevalence of finite mathematics in modern society, with applications which are accessible to student experimentation Primarily intended for Liberal Arts and Business majors. (ATTR: ARTS, CAQ) MATH 030 - History of Mathematics This is a one semester course on selected topics in the history of methematical ideas. Topics covered may include the notions of limit, infinity, area, parallelism, pi, transcendental numbers, number systems, mensuration, polynomials, cosmology, map coloring, logic, proof, abstraction, generalization, quadrature, trisection, or algebraic structure. The history of a given idea will be traced, and relevant problems will be presented. This course is intended for students in all schools of the College. Mathematics majors may take this class for elective credit but it does not count towards the requirements for the major. Offered spring semester. (ATTR: ARTS, CAQ) MATH 050 - Preparation for Calculus A study of the background material needed for calculus with emphasis on functions. The course includes a study of relations, functions and graphs, polynomials, solving equations and inequalities, rational and radical functions, logarithmic and exponential functions, trigonometric functions both right angle and analytic, vectors, polar and parametric equations, and an introduction to the conic sections. Students must purchase an approved graphing calculator prior to beginning this course. (ATTR: ARTS) MATH 110 - Calculus I Courses MATH- 110, 120, and 210 provide foundation for all upper level mathematics courses. Main topics considered during the first semester: functions, limits, continuity, differentiation, the chain-rule, antiderivatives, the definite integral, Fundamental Theorem of Calculus and trigonometric functions. Applications of all topics are emphasized. Three hours of lecture and one hour and twenty minutes of laboratory per week. Lab fee. Students must purchase an approved graphing calculator prior to begining this course. (ATTR: ARTS, CAQ) MATH 120 - Calculus II This course completes the calculus of elementary transcendental functions. It also includes techniques of integration, indeterminate forms, L'Hospital's Rule, improper integrals, and introduction to sequences, infinite series and power series. Students apply concepts to work, volume, arc length, and other physical phenomena. Three hours of lecture and one hour and twenty minutes of laboratory each week. Lab fee. Students must purchase an approved graphing calculator prior to beginning this course. (Effective Spring Semester 1994.) (ATTR: ARTS CAQ) MATH 191 - Mathematical Problem Solving An introduction to the art and craft of mathematical problem solving. Students interact in a seminar setting, discussing and solving interesting mathematical problems. Oral presentations of problems and solutions are a required part of this course. There are no prerequisites. (ATTR:ARTS) MATH 210 - Calculus III This course completes the Calculus sequence. The topics covered are vectors in the plane and in a three dimensional space, functions of several variables, partial differentiation, the chain rules, multiple integration including cylindrical and spherical coordinate systems and the theorems of Green and Stokes. Students apply these concepts to physical applications. (ATTR: ARTS) MATH 250 - Discrete Structures I This course includes a study of mathematical structures most frequently encountered in Computer Science. Topics covered include sets, functions, mathematical induction, complexity analysis of algorithms, counting methods including probability, recurrence relations, graphs, trees, Boolean logic, and relations. Proofs using mathematical induction will be emphasized. Other proof techniques will be developed. Three hours of lecture and 80 minutes of lab each week. Offered Fall Semester. Cross-listed as CSIS-251. (ATTR: ARTS) MATH 301 - Foundations of Mathematics The course introduces logic, set theory and techniques of mathematical proof. The main emphasis of the course is on composing logically correct mathematical arguments. Oral and written presentation of solutions and proofs are a required part of the course, (ATTR: ARTS, MHUL) MATH 310 - Intro to Modern Algebra This course is an introduction to the elementary theory of groups and rings, developed axiomatically. Other topics covered are subgroups and closets, normal subgroups, factor groups, homomorphism and isomorphism of groups and rings, fundamental theorems for groups and rings. Offered Fall Semester. (ATTR: ARTS, MHUL) MATH 325 - Differential Equations A study of differential equations using analytic, numerical and graphical techniques. Emphasis is placed on the formula- tion of models that result in a differential equation and the interpretation of solutions. Slope fields, graphs of solutions (analytic and numerical), vector fields and solution curves in the phase plane will be used to gain a better understanding of differential equations. Computer based tools will be used to investigate the behavior of solutions both numerically and graphically. Offered Spring Semester. ATTR: ARTS, MHUL MATH 330 - Intro to Applied Mathematics I In this course there will be applications of first and second order differential equations and linear algebra. The series solutions of the differential equations of Bessel and Legendre are studied in detail. Other topics include Fourier series and expansions as well as other series comprised of orthogonal functions. Applications of these expansions will be discussed as time allows. (ATTR: ARTS, MUHL) MATH 340 - Introduction to Number Theory A discussion of the basic properties of the set of integers. Prime numbers and the Euclidean Algorithm. Number- theoretic functions, especially the Euler phi-function. Linear congruences and their applications to the solution of Diophantine Equations. Exponents and primitive roots. Quad- ratic residues and the Law of Quadratic Reciprocity. Offered in Spring Semester. (ATTR: ARTS, MHUL) MATH 371 - Probability for Statistics The course introduces mathematical probability to understand variation and variability. Methods of enumeration, con- ditional probability, independent events, and Bayes' Theorem are developed in a general environment. Among the continuous and discrete probability distributions derived and studied are the Bernoulli distribution and distributions based on it, the uniform, exponential, normal, Gamma and Chi Square distributions. The Central Limit Theorem leads to approximations for discrete distributions. Chebyshev's In- equality prepares the student for Inferential Statistics. (may be taken concurrently). Offered Spring semester. (ATTR: ARTS, MHUL) MATH 425 - Differential Geometry This course is an introduction to the theory of curves and surfaces in the three-dimensional Euclidean space. Topics include curve arc length, curvature, torsion, the Frenet n-frame, the first and second fundamental forms of a surface, normal and principal curvatures, Gaussian and the mean curvatures, isometries of surfaces, and geodesic curves on a surface. (ATTR: ARTS, MHUL) MATH 460 - Topology This is a one semester introductory course in Topology. The topics covered include: Open and closed sets, topologies on general point sets, connectedness, compactness, continuity, product and quotient topologies, and metric spaces. Applica- tions to other areas in mathematics (principally geometry and analysis) will be explored. Offered Spring Semester. (ATTR: ARTS,MHUL) MATH 470 - Mathematical Statistics Statistical tests for multivariable problems are developed and applied to real data sets. The computer and the SPSS package will be used. Offered Fall Semester. (ATTR: ARTS, MHUL) MATH 480 - Mathematics of Finance This course builds on the knowledge base contained in previous courses taken by actuarial students. The goal is to reinforce understanding of the fundamental concepts of financial mathematics, and how those concepts are applied in calculating present and accumulated values for various streams of cash flows as a basis for future use. Students will review basic financial instruments and expand their knowledge base to more modern financial analysis using yield curves, spot rates and immunization. Finally, students will be introduced to the concept of risk management and understand how principles such as derivatives, forwards, futures, short and long positions, call and put options, spreads, collars, hedging, arbitrage, and swaps affect a firms' risk. Pre-requisite Finc 301, Finc 315 and Math 120, or permission of instructor. (ATTR: ARTS, BUS, MHUL) MATH 490 - Mathematics Seminar Consideration of a mathematical topic selected on the basis of faculty and student interest. Designed for students with good mathematical backgrounds. May be taken twice with different topic. Permission of instructor or department required for registration. Offered Spring Semester. (ATTR: ARTS, MHUL) MATH 499 - Independent Study in Math Study or research on an advanced mathematics topic under the tutelage of a qualified faculty member. May be taken more than one semester. Permission of faculty mentor and department head required for registration. (ATTR: ARTS, MHUL)
Trigonometry 9780495108351 ISBN: 0495108359 Edition: 6 Pub Date: 2007 Publisher: Thomson Learning Summary: Gain a solid understanding of the principles of trigonometry and how these concepts apply to real life with McKeague/Turner's TRIGONOMETRY, Sixth Edition. This books proven approach presents contemporary concepts in brief, manageable sections using current, detailed examples and interesting applications. Captivating illustrations drawn from Lance Armstrongs cycling success, the Ferris wheel, and even the human cannon...ball show trigonometry in action. Unique Historical Vignettes offer a fascinating glimpse at how many of the central ideas in trigonometry began. McKeague, Charles P. is the author of Trigonometry, published 2007 under ISBN 9780495108351 and 0495108359. Four hundred fifty three Trigonometry textbooks are available for sale on ValoreBooks.com, one hundred seventy used from the cheapest price of $17.64, or buy new starting at $44
Linear Algebra 9780135367971 ISBN: 0135367972 Edition: 2 Pub Date: 1971 Publisher: Prentice Hall Summary: This introduction to linear algebra features intuitive introductions and examples to motivate important ideas and to illustrate the use of results of theorems. Linear Equations; Vector Spaces; Linear Transformations; Polynomials; Determinants; Elementary canonical Forms; Rational and Jordan Forms; Inner Product Spaces; Operators on Inner Product Spaces; Bilinear Forms For all readers interested in linear algebra. ...> Hoffman, Kenneth is the author of Linear Algebra, published 1971 under ISBN 9780135367971 and 0135367972. Four hundred thirty six Linear Algebra textbooks are available for sale on ValoreBooks.com, twenty one used from the cheapest price of $51.30, or buy new starting at $80.71
, Student Edition From the first day your students begin to learn the vocabulary of algebra until the day they take final exams and standardized tests, these programs ...Show synopsisFrom the first day your students begin to learn the vocabulary of algebra until the day they take final exams and standardized tests, these programs strengthen student understanding and provide the tools students need
This text combines the theoretical instruction of calculus with current best-practise strategies.This text combines the theoretical instruction of calculus with current best-practise
High School Pre-Calculus Tutor 9780878919109 ISBN: 0878919104 Publisher: Research & Education Assn Summary: Algebra * Biology * Chemistry * Earth Science Geometry * Physics * Pre-Algebra * Pre-Calculus * Probability Trigonometry * Math Skills for SAT * Verbal Skills for SAT "With the Tutor Books, it's Easy to learn difficult subjects." The best help in preparing for homework and exams Includes every type of problem that may be assigned by your teacher or given on a test Guides you by working out problems in step-by-step de...tail Each "Tutor" helps you understand the subject fully, no matter which textbook you use. Fogiel, M. is the author of High School Pre-Calculus Tutor, published under ISBN 9780878919109 and 0878919104. Two hundred thirty three High School Pre-Calculus Tutor textbooks are available for sale on ValoreBooks.com, one hundred twenty seven used from the cheapest price of $0.01, or buy new starting at $11.96.[read more
128540212X 9781285402123 Practical Problems in Mathematics for Masons:Newly revised for the 3rd Edition, PRACTICAL PROBLEMS IN MATHEMATICS FOR MASONS provides the quantitative skills you need for success in the workplace. Starting with the basics, this practical worktext uses straightforward language and clear organization to develop confidence quickly with helpful hints. This book guides you through the math most commonly used in masonry reinforcing your knowledge of key math principles from whole numbers and decimals to fractions and percentages. Next, step-by-step discussions of volume, area, square roots, and the Pythagorean Theorem provide the foundation masons need to properly measure projects, align walls, and estimate quantities of materials. Throughout PRACTICAL PROBLEMS IN MATHEMATICS FOR MASONS, 3RD Edition many examples, illustrations, and practice word problems help develop logical reasoning skills while developing your awareness of basic masonry terms and practices. Back to top Rent Practical Problems in Mathematics for Masons 3rd edition today, or search our site for John textbooks. Every textbook comes with a 21-day "Any Reason" guarantee. Published by CENGAGE Learning.
Get Rid of Facebook Distraction on your Device and Get Started Studying with Maths Practice. Follow me on Twitter: @senimii +1 me on Google Play GCSE(UK), West Africa Examination Council (WAEC), JAMB, UTME, and Several Other Exams from Different Part Of The World 420 unique multiple-choice test questions, Maths Examstutor is a comprehensive GCSE Maths exam revision app. Instant feedback for each question helps you identifying the correct response to any questions you get wrong. Reinforcing your understanding of key topics you can be examined on at GCSE. Combined with the facility to link to further revision support on examstutor.com used by leading schools and colleges across the UK, this app will be updated with additional topic tests and questions throughout your studies. Revise a specific Topic, or create Random Tests, with questions drawn from all key topics in a specific Unit, or from across the entire GCSE, including Foundation and Higher courses. GCSE Maths is a qualification studied by UK and international students prior to attending College. This app can be used by anyone wishing to refresh of improve their understanding of Mathematics. Features include: · Topic Tests: Covering Foundation and Higher exam topics · Random Tests: Choose the number of questions randomly drawn from either the entire A level or the unit you are currently revising. · Instant Feedback : Correct Answers identified if you get a question wrong, reinforcing learning. · Report Card : tracking your performance in all the tests you take, whilst charting your understanding of each topic prior to you sitting exams. This interactive maths resource will identify trouble areas and suggest further studies, and is full of video tutorials and real-life examples to help you revise and practise, progress and get top exam results. With Collins Revision Algebra you can now hone your mathematics skills wherever you are. • Be inspired by interactive animations, exciting video clips of students teaching a problem, real-life examples of maths at work, worked exam questions, tutorials and more • Choose precisely which topics to revise and practise with material corresponding to the Collins New GCSE Maths scheme • Test yourself with interactive assessment questions that identify trouble areas and suggest relevant further revision Videos are downloaded separately by the app, directly to your device, upon installation. Collect all four Apps covering all four GCSE maths strands, for a total of 900 practice questions, 300 assessment questions and 130 video clips! This app enables you to visualise graphically what happens when you change the values of a, b and c in the quadratic equation y = ax² + bx + c. Generally the shape of the graph is a parabola. But is it always parabolic? Where does it cross the x and y axes – if at all? Where is the vertex – if there is one? This and other questions can be answered using this app. The main features of the app are: * An interactive approach to help deepen understanding of Quadratic Equations * Visualising the quadratic equation and its x/y intercepts and vertex graphically * Zoom in/out graphically * On-screen take-by-the-hand walkthrough to help highlight interesting mathematical features * A Quadratic Calculator to calculate the x/y intercepts, vertex, factored and vertex forms of the quadratic from chosen values for a, b and c (for real values). The PETSS is an educational app designed specifically for students in Secondary Schools taking various examinations such as the WAEC, NECO and JAMB. It is an innovation in learning that dramatically improves the performance of students taking various examinations. Audio-visual classroom lessons: The PETSS provides an audio-visual recording of lessons conducted by top teachers. The student can watch and listen to the same lesson over and over again as many times as he wishes until he has a complete grasp of the topic. The recordings allow retention of concepts by over 25% more, when compared to just reading from books. NERDC Curriculum-based textbooks for SSCE: The Tablet is pre-loaded with textbooks based on curriculum of the NERDC for Senior Secondary Schools for each subject. The student can highlight and bookmark portions of text for later reference. Past Question Papers and Mock Examinations: Students generally want to test their knowledge of the subject they are studying by attempting past examination questions in that subject. The PETSS is pre-loaded with different past exam papers from WAEC, NECO and JAMB. The student would be able to attempt to answer these questions. Answers are provided so he can easily determine his own knowledge of the subject matter. Apart from attempting past question papers, the PETSS can also generate mock examination papers that students can try in a simulated examination condition to determine how well he would perform in a real examination situation. The questions would be selected by the system based on the same process that examiners use in creating question papers. The MobileLessons app delivers rich and interactive educational content, this includes tutorials on a wide variety of subjects, presenter-led videos on solved essay exams and interactive multiple-choice exams. Hundreds of tutorials, solved exams and multiple-choice quizzes, tests and exams are added daily. Features of the app (1.) High Quality video lectures, this includes teacher videos, beautiful slides, mouse pointer, writing and drawing on the screen (2.) Three level navigation - This allows for structured and accessible navigation of lectures and content. See screenshots (3.) Free text search - The user can search by simply typing in any text and the result will be filtered in the three levels. (4.) Multiple choice test - Multiple choice test/exams for all past questions papers in wide variety of subject across different countries. (5.) Country Search - Users can narrow their search according to country for selecting standardized/syndicated exams like UTME, WASSC, ACA and tutorials. The exordium of the computer Based Test by JAMB brought about the Development of MOBILE JAMB CBT Application. This App is being developed to provide Jamb candidates with faster, immediate and reliable access to Jamb Computer Based Test (CBT) in any subject of their choice with NO internet connection. The users are being supplied with questions based on the subject and year selected and the user is being graded after the submission of the Examination and the answer to each question are also provided. Apart from the provision of faster and easier access to Jamb Past Questions,it also saves the cost of connecting to the internet for practising CBT questions or purchase of the past question series papers. Since JAMB has gone CBT, JAMB candidates are not to be caught unaware of this latest development. The App also comes with a timer, to keep you on your toes while solving the questions The Maths GCSE Diagnostic Tool is a skills based assessment program. The app successfully highlights your strengths and your areas to develop within the subject. This is a very useful tool to use prior to any test to help rank which revision topics are of the most importance. ABOUT THE APP: The app is setup in such a way to guide you through a wide range of Mathematical topics, divided into 3 easy units to help you manage your revision: Unit 1 - Statistics and Number (calculator allowed), Unit 2 - Number and Algebra (calculator not allowed) and Unit 3 - Geometry and Algebra (calculator allowed). The diagnostic tool is applicable to both the linear and the modular system as it assesses generic skill based Mathematical knowledge; it therefore suitably matches the AQA, Edexcel or OCR schemes of learning. Each unit is provided as either a higher or as a foundation option to allow you to target your desired tier of final paper. INSTRUCTIONS: After installation, you are presented with a login screen. You will need to create your own account following the on screen instructions. Keep your login details safe as all future results will be stored under your account. This incredibly powerful tool then helps you to start identifying areas you need to revise. By answering each of the online questions, the app highlights the objectives you have successfully completed and which ones you will need to work on. After some targeted revision, you can then return back to the app to see if you have improved. With each access, the questions are refreshed so you can assess yourself with a similar problem but with different numbers. SUPPORT: Before rating the app, please let me know of any suggestions you might have on how I might improve the app. Any topics you think I may have missed or you happen to perhaps find some glaring glitches, then please email me first at mrwslab@gmail.com. The app has taken a considerable amount of my personal time to develop so please give it 5 stars to say "thank you". Physics Practical formulas focuses on students learning or new to physics. The app covers tutorials, solver, quiz, formulas and dictionary. Users are free to test their understanding of physics with the assignment and quiz options. It contains a comprehensive physics tutorials that covers many topics and the dictionary section will help you to check the meaning of different physics words. This app also has a physics note section where you can jot or save notes of items you want to remember or a summary of certain concept in physics. Physics practical formulas basically covers syllabus for exams like WAEC, NECO, JAMB, KCSE, Post JAMB and GCE. Although eveyone can still use it. The following toipcs are covered Physics as a science Kinematics Fluid Scalar and Vector Force Circular Motion Energy Momentum Heat Energy and Thermodynamics Optics Waves Magnetism Electricity Modern Physics Nuclear Physics Disclaimer: The questions and solutions section uses Past WAEC exam questions and solutions which is provided by WAEC for students planning to sit of WAEC exams If you have a suggestion or issue with this app please kindly let me know through my email so that I will attend to it immediately. Remember to rate this app To guide you through the Maths iGCSE, our tutor-led revision videos start by developing your basic mathematical skills, and progress you onto more advanced levels of learning as you build your confidence and understanding. Whether you're studying the Cambridge or Edexcel Maths iGCSE, each tutor-led lesson begins with a clear set of learning objectives so you can easily see how it fits within the overall programme of study. Each clip is presented by a fully-qualified teacher and, by combining easy to follow content with green-screen technology, you won't even realise you're learning. Please note. *These videos are streamed on-demand for immediate viewing and require an internet connection. We recommend using a WI-FI connection to avoid charges incurred as a result of exceeding your data allowance. The fastpassMATHS app gives you a great way to study for your HSC, GCSE or other entry level of high school exams anytime, anywhere on your phone. On a 5 minute break! Waiting for the bus! On the bus! With your mates! The free version comes with a set of flash cards and a notes-taking section, plus 50% of the easy exercises with built-in randomization and marking. The medium and hard questions are currently available for a small cost. Make your purchases through the app and you will receive all our additional content and feature updates at no extra cost! - Access over 30,000 past questions and their solutions for JAMB, WAEC, NECO and NABTEB exams, in an organized manner. - Access all past questions and their solutions without any Internet Connection, even in remote and rural areas. - Carry all past question & answer booklets for all subjects in your mobile phone. - Enables you search for a particular question keyword in any subject and get the answer and explanations. Like a "google" for past questions. - Gives you an idea of what JAMB CBT environment feels like. - Comes with flexible and reliable 1 year of SMS alerts for your choice school as stated in your profile. - Comes with a FREE copy of Admission 101 - A guide and an eye opener to all the pitfalls you should avoid right from filling your JAMB form, until you get into school and finally matriculate. - Prepares you for CBT and also Post-UTME exams in your school of choice. - Avoid expensive admission sorting by encouraging learning. With this Myschool App and constant practice, you are sure of your merit admission in the coming session. The Jamb Examination Preparation Kit otherwise known as JAMB Prep is a Computer based interactive multimedia software, designed to prepare Post-secondary students seeking to gain admission into Nigeria University an opportunity to practise in a computer simulated examination condition close to what is obtainable in the real time examination. JAMB Prep is composed of past examinations questions from JAMB compiled over a period of ten years of the JAMB Examination. This GCSE mathematics app allows you to learn transformations in a way that is not available from a text book. By entering the interactive graphs you can plot different shapes and transform them in many different ways. You will be taught about translation, enlargement, reflection and rotation through small lessons. Each topic is then followed by an interactive graph where you can play with various factors, such as centre of enlargements and angles of rotation. After you have explored each topic, you can then answer a set of questions. This app really complements what you will learn about transformations in school. It is the perfect way to fully understand how different transformations are working and help you prepare for your exams.
This site contains lots of helpful hints about how to easily type different mathematical expressions in e-mail messages (or... see more This site contains lots of helpful hints about how to easily type different mathematical expressions in e-mail messages (or in online discussion forums). This might be particularly helpful for online instructors who want students to talk about problems and share their work with others within the online environment. If the spaces and structures that result from facilities planning are to provide a safe, engaging, efficient, and... see more If the spaces and structures that result from facilities planning are to provide a safe, engaging, efficient, and cost-effective environment for students and faculty for many years, they must be planned by and for the community that is to use them. Those who understand the nature of observation, investigation, problem-solving, and communication that is at the heart of the scientific way of knowing must have leadership roles in this process. This handbook is intended for use by colleges and universities that are thinking about, or in the process of planning for, new or renovated spaces for their undergraduate programs in science and mathematics, but the steps for the processes illustrated would also be useful to those who plan for K12 science facilities. Structures for Science includes materials, expanded and edited for publication, used at PKAL Facilities Workshops. The handbook also includes material developed specifically for this PKAL report about the planning and design process. The Beamer package is a LaTeX class for creating presentations that are held using a projector, but it can also be used to... see more The Beamer package is a LaTeX class for creating presentations that are held using a projector, but it can also be used to create transparency slides. The Beamer is perfect for creating a presentation with a large amount of mathematical formulas. It is freely available for download. A collection of over 50 full-text essays and links to additional sites that focus on constructivism and education collected... see more A collection of over 50 full-text essays and links to additional sites that focus on constructivism and education collected by the Maryland Collaborative for Teacher Preparation: A State-Wide Pre-Service Program to Prepare Special Teachers for Elementary and Middle School Science and Mathematics
ronic Circuits: Logic Fundamentals, Types & Application03 Stock Status: In Stock About This is the last course in a three-part series which teaches students the fundamentals of electronic circuits, and some common applications as well as introduces students to the principles and functioning of many common electronic circuits. In this course, AND, OR logic is explained and calculated as well as an explanation of the binary and hexadecimal number systems and Boolean algebra is presented to the student. -Relay circuits that are arranged to perform AND, OR, and inversion functions -Compute truth tables for the inverter and for the AND and OR functions -Binary number system & hexadecimal number system -Logic symbols and truth tables for NAND and NOR gates
A First Course in Geometry (Dover Books on Mathematics) Synopses & Reviews Publisher Comments: This introductory college-level text presents concepts in an intuitive manner, building upon skills developed in previous sections. Topics include the language of mathematics, geometric sets of points, separation and angles, triangles, parallel lines, similarity, polygons and area, circles, and space and coordinate geometry. Includes problem sets, review problems, hints, and outlines. 1974
Practice Makes Perfect Precalculus - 12 edition Summary: Don't be perplexed by precalculus. Master this math with practice, practice, practice! Practice Makes Perfect: Precalculus is a comprehensive guide and workbook that covers all the basics of precalculus that you need to understand this subject. Each chapter focuses on one major topic, with thorough explanations and many illustrative examples, so you can learn at your own pace and really absorb the information. You get to apply your knowledge and practice what you've learned through...show more a variety of exercises, with an answer key for instant feedback. Offering a winning solution for getting a handle on math right away, Practice Makes Perfect: Precalculus is your ultimate resource for building a solid understanding of precalculus fundamentals
First half of this highly regarded book covers complex number plane; functions and limits; Riemann surfaces, the definite integral; power series; meromorphic functions, and much more. The second half deals with potential theory; ordinary differential equations; Fourier transforms; Laplace transforms ... read more A Collection of Problems on Complex Analysis by L. I. Volkovyskii, G. L. Lunts, I. G. Aramanovich Over 1500 problems on theory of functions of the complex variable; coverage of nearly every branch of classical function theory. Answers and solutions. Complex Variables by Francis J. Flanigan Contents include calculus in the plane; harmonic functions in the plane; analytic functions and power series; singular points and Laurent series; and much more. Numerous problems and solutions. 1972Advanced Calculus by Avner Friedman Intended for students who have already completed a one-year course in elementary calculus, this two-part treatment advances from functions of one variable to those of several variables. Solutions. 1971Advanced Calculus: An Introduction to Classical Analysis by Louis Brand A course in analysis that focuses on the functions of a real variable, this text introduces the basic concepts in their simplest setting and illustrates its teachings with numerous examples, theorems, and proofs. 1955 edition. A Course in Advanced Calculus by Robert S. Borden An excellent undergraduate text examines sets and structures, limit and continuity in En, measure and integration, differentiable mappings, sequences and series, applications of improper integrals, more. Problems with tips and solutions for some. Advanced Calculus of Several Variables by C. H. Edwards, Jr. Modern conceptual treatment of multivariable calculus, emphasizing interplay of geometry and analysis via linear algebra and the approximation of nonlinear mappings by linear ones. Over 400 well-chosen problems. 1973 edition. Concepts of Modern Mathematics by Ian Stewart In this charming volume, a noted English mathematician uses humor and anecdote to illuminate the concepts of groups, sets, subsets, topology, Boolean algebra, and other mathematical subjects. 200
Pre-Algebra: Exponents and Roots Find study help on exponents and roots for pre-algebra. Use the links below to select the specific area of exponents and roots you're looking for help with. Each guide comes complete with an explanation, example problems, and practice problems with solutions to help you learn exponents and roots for pre-algebra.
Citation Manager " Part One: Connecting Mathematics with Work and Life ." High School Mathematics at Work: Essays and Examples for the Education of All StudentsPart One— Connecting Mathematics with Work and Life OCR for page 7 This page in the original is blank. OCR for page 7 --> Overview Mathematics is the key to opportunity. No longer just the language of science, mathematics now contributes in direct and fundamental ways to business, finance, health, and defense. For students, it opens doors to careers. For citizens, it enables informed decisions. For nations, it provides knowledge to compete in a technological community. To participate fully in the world of the future, America must tap the power of mathematics. (NRC, 1989, p. 1) The above statement remains true today, although it was written almost ten years ago in the Mathematical Sciences Education Board's (MSEB) report Everybody Counts (NRC, 1989). In envisioning a future in which all students will be afforded such opportunities, the MSEB acknowledges the crucial role played by formulae and algorithms, and suggests that algorithmic skills are more flexible, powerful, and enduring when they come from a place of meaning and understanding. This volume takes as a premise that all students can develop mathematical understanding by working with mathematical tasks from workplace and everyday contexts. The essays in this report provide some rationale for this premise and discuss some of the issues and questions that follow. The tasks in this report illuminate some of the possibilities provided by the workplace and everyday life. OCR for page 7 --> Contexts from within mathematics also can be powerful sites for the development of mathematical understanding, as professional and amateur mathematicians will attest. There are many good sources of compelling problems from within mathematics, and a broad mathematics education will include experience with problems from contexts both within and outside mathematics. The inclusion of tasks in this volume is intended to highlight particularly compelling problems whose context lies outside of mathematics, not to suggest a curriculum. The operative word in the above premise is "can." The understandings that students develop from any encounter with mathematics depend not only on the context, but also on the students' prior experience and skills, their ways of thinking, their engagement with the task, the environment in which they explore the task—including the teacher, the students, and the tools—the kinds of interactions that occur in that environment, and the system of internal and external incentives that might be associated with the activity. Teaching and learning are complex activities that depend upon evolving and rarely articulated interrelationships among teachers, students, materials, and ideas. No prescription for their improvement can be simple. This volume may be beneficially seen as a rearticulation and elaboration of a principle put forward in Reshaping School Mathematics: Principle 3: Relevant Applications Should be an Integral Part of the Curriculum. Students need to experience mathematical ideas in the context in which they naturally arise—from simple counting and measurement to applications in business and science. Calculators and computers make it possible now to introduce realistic applications throughout the curriculum. The significant criterion for the suitability of an application is whether it has the potential to engage students' interests and stimulate their mathematical thinking. (NRC, 1990, p. 38) Mathematical problems can serve as a source of motivation for students if the problems engage students' interests and aspirations. Mathematical problems also can serve as sources of meaning and understanding if the problems stimulate students' thinking. Of course, a mathematical task that is meaningful to a student will provide more motivation than a task that does not make sense. The rationale behind the criterion above is that both meaning and motivation are required. The motivational benefits that can be provided by workplace and everyday problems are worth mentioning, for although some students are aware that certain mathematics courses are necessary in order to gain entry into particular career paths, many students are unaware of how particular topics or problem-solving approaches will have relevance in any workplace. The power of using workplace and everyday problems to teach mathematics lies not so much in motivation, however, for no con- OCR for page 7 --> text by itself will motivate all students. The real power is in connecting to students' thinking. There is growing evidence in the literature that problem-centered approaches—including mathematical contexts, "real world" contexts, or both—can promote learning of both skills and concepts. In one comparative study, for example, with a high school curriculum that included rich applied problem situations, students scored somewhat better than comparison students on algebraic procedures and significantly better on conceptual and problem-solving tasks (Schoen & Ziebarth, 1998). This finding was further verified through task-based interviews. Studies that show superior performance of students in problem-centered classrooms are not limited to high schools. Wood and Sellers (1996), for example, found similar results with second and third graders. Research with adult learners seems to indicate that "variation of contexts (as well as the whole task approach) tends to encourage the development of general understanding in a way which concentrating on repeated routine applications of algorithms does not and cannot" (Strässer, Barr, Evans, & Wolf, 1991, p. 163). This conclusion is consistent with the notion that using a variety of contexts can increase the chance that students can show what they know. By increasing the number of potential links to the diverse knowledge and experience of the students, more students have opportunities to excel, which is to say that the above premise can promote equity in mathematics education. There is also evidence that learning mathematics through applications can lead to exceptional achievement. For example, with a curriculum that emphasizes modeling and applications, high school students at the North Carolina School of Science and Mathematics have repeatedly submitted winning papers in the annual college competition, Mathematical Contest in Modeling (Cronin, 1988; Miller, 1995). The relationships among teachers, students, curricular materials, and pedagogical approaches are complex. Nonetheless, the literature does supports the premise that workplace and everyday problems can enhance mathematical learning, and suggests that if students engage in mathematical thinking, they will be afforded opportunities for building connections, and therefore meaning and understanding. In the opening essay, Dale Parnell argues that traditional teaching has been missing opportunities for connections: between subject-matter and context, between academic and vocational education, between school and life, between knowledge and application, and between subject-matter disciplines. He suggests that teaching must change if more students are to learn mathematics. The question, then, is how to exploit opportunities for connections between high school mathematics and the workplace and everyday life. Rol Fessenden shows by example the importance of mathematics in business, specifically in making marketing decisions. His essay opens with a dialogue among employees of a company that intends to expand its business into OCR for page 7 --> Japan, and then goes on to point out many of the uses of mathematics, data collection, analysis, and non-mathematical judgment that are required in making such business decisions. In his essay, Thomas Bailey suggests that vocational and academic education both might benefit from integration, and cites several trends to support this suggestion: change and uncertainty in the workplace, an increased need for workers to understand the conceptual foundations of key academic subjects, and a trend in pedagogy toward collaborative, open-ended projects. Further-more, he observes that School-to-Work experiences, first intended for students who were not planning to attend a four-year college, are increasingly being seen as useful in preparing students for such colleges. He discusses several such programs that use work-related applications to teach academic skills and to prepare students for college. Integration of academic and vocational education, he argues, can serve the dual goals of "grounding academic standards in the realistic context of workplace requirements and introducing a broader view of the potential usefulness of academic skills even for entry level workers." Noting the importance and utility of mathematics for jobs in science, health, and business, Jean Taylor argues for continued emphasis in high school of topics such as algebra, estimation, and trigonometry. She suggests that workplace and everyday problems can be useful ways of teaching these ideas for all students. There are too many different kinds of workplaces to represent even most of them in the classrooms. Furthermore, solving mathematics problems from some workplace contexts requires more contextual knowledge than is reasonable when the goal is to learn mathematics. (Solving some other workplace problems requires more mathematical knowledge than is reasonable in high school.) Thus, contexts must be chosen carefully for their opportunities for sense making. But for students who have knowledge of a workplace, there are opportunities for mathematical connections as well. In their essay, Daniel Chazan and Sandra Callis Bethell describe an approach that creates such opportunities for students in an algebra course for 10th through 12th graders, many of whom carried with them a "heavy burden of negative experiences" about mathematics. Because the traditional Algebra I curriculum had been extremely unsuccessful with these students, Chazan and Bethell chose to do something different. One goal was to help students see mathematics in the world around them. With the help of community sponsors, Chazen and Bethell asked students to look for mathematics in the workplace and then describe that mathematics and its applications to their classmates. The tasks in Part One complement the points made in the essays by making direct connections to the workplace and everyday life. Emergency Calls (p. 42) illustrates some possibilities for data analysis and representation by discussing the response times of two ambulance companies. Back-of-the-Envelope Estimates (p. 45) shows how quick, rough estimates and calculations OCR for page 7 --> are useful for making business decisions. Scheduling Elevators (p. 49) shows how a few simplifying assumptions and some careful reasoning can be brought together to understand the difficult problem of optimally scheduling elevators in a large office building. Finally, in the context of a discussion with a client of an energy consulting firm, Heating-Degree-Days (p. 54) illuminates the mathematics behind a common model of energy consumption in home heating. References Cronin, T. P. (1988). High school students win "college" competition. Consortium: The Newsletter of the Consortium for Mathematics and Its Applications, 26, 3, 12. Miller, D. E. (1995). North Carolina sweeps MCM '94.SIAM News, 28 (2). National Research Council. (1989). Everybody counts: A report to the nation on the future of mathematics education. Washington, DC: National Academy Press. National Research Council. (1990). Reshaping school mathematics: A philosophy and framework for curriculum. Washington, DC: National Academy Press. Schoen, H. L. & Ziebarth, S. W. (1998). Assessment of students' mathematical performance (A Core-Plus Mathematics Project Field Test Progress Report). Iowa City: Core Plus Mathematics Project Evaluation Site, University of Iowa. Strässer, R., Barr, G. Evans, J. & Wolf, A. (1991). Skills versus understanding. In M. Harris (Ed.), Schools, mathematics, and work (pp. 158-168). London: The Falmer Press. Wood, T. & Sellers, P. (1996). Assessment of a problem-centered mathematics program: Third grade. Journal for Research in Mathematics Education, 27(3), 337-353. OCR for page 7 --> 1— Mathematics as a Gateway to Student Success DALE PARNELL Oregon State University The study of mathematics stands, in many ways, as a gateway to student success in education. This is becoming particularly true as our society moves inexorably into the technological age. Therefore, it is vital that more students develop higher levels of competency in mathematics.1 The standards and expectations for students must be high, but that is only half of the equation. The more important half is the development of teaching techniques and methods that will help all students (rather than just some students) reach those higher expectations and standards. This will require some changes in how mathematics is taught. Effective education must give clear focus to connecting real life context with subject-matter content for the student, and this requires a more ''connected" mathematics program. In many of today's classrooms, especially in secondary school and college, teaching is a matter of putting students in classrooms marked "English," "history," or "mathematics," and then attempting to fill their heads with facts through lectures, textbooks, and the like. Aside from an occasional lab, workbook, or "story problem," the element of contextual teaching and learning is absent, and little attempt is made to connect what students are learning with the world in which they will be expected to work and spend their lives. Often the frag- OCR for page 7 --> mented information offered to students is of little use or application except to pass a test. What we do in most traditional classrooms is require students to commit bits of knowledge to memory in isolation from any practical application—to simply take our word that they "might need it later." For many students, "later" never arrives. This might well be called the freezer approach to teaching and learning. In effect, we are handing out information to our students and saying, "Just put this in your mental freezer; you can thaw it out later should you need it." With the exception of a minority of students who do well in mastering abstractions with little contextual experience, students aren't buying that offer. The neglected majority of students see little personal meaning in what they are asked to learn, and they just don't learn it. I recently had occasion to interview 75 students representing seven different high schools in the Northwest. In nearly all cases, the students were juniors identified as vocational or general education students. The comment of one student stands out as representative of what most of these students told me in one way or another: "I know it's up to me to get an education, but a lot of times school is just so dull and boring. … You go to this class, go to that class, study a little of this and a little of that, and nothing connects. … I would like to really understand and know the application for what I am learning." Time and again, students were asking, "Why do I have to learn this?" with few sensible answers coming from the teachers. My own long experience as a community college president confirms the thoughts of these students. In most community colleges today, one-third to one-half of the entering students are enrolled in developmental (remedial) education, trying to make up for what they did not learn in earlier education experiences. A large majority of these students come to the community college with limited mathematical skills and abilities that hardly go beyond adding, subtracting, and multiplying with whole numbers. In addition, the need for remediation is also experienced, in varying degrees, at four-year colleges and universities. What is the greatest sin committed in the teaching of mathematics today? It is the failure to help students use the magnificent power of the brain to make connections between the following: subject-matter content and the context of use; academic and vocational education; school and other life experiences; knowledge and application of knowledge; and one subject-matter discipline and another. Why is such failure so critical? Because understanding the idea of making the connection between subject-matter content and the context of application OCR for page 7 --> is what students, at all levels of education, desperately require to survive and succeed in our high-speed, high-challenge, rapidly changing world. Educational policy makers and leaders can issue reams of position papers on longer school days and years, site-based management, more achievement tests and better assessment practices, and other "hot" topics of the moment, but such papers alone will not make the crucial difference in what students know and can do. The difference will be made when classroom teachers begin to connect learning with real-life experiences in new, applied ways, and when education reformers begin to focus upon learning for meaning. A student may memorize formulas for determining surface area and measuring angles and use those formulas correctly on a test, thereby achieving the behavioral objectives set by the teacher. But when confronted with the need to construct a building or repair a car, the same student may well be left at sea because he or she hasn't made the connection between the formulas and their real-life application. When students are asked to consider the Pythagorean Theorem, why not make the lesson active, where students actually lay out the foundation for a small building like a storage shed? What a difference mathematics instruction could make for students if it were to stress the context of application—as well as the content of knowledge—using the problem-solving model over the freezer model. Teaching conducted upon the connected model would help more students learn with their thinking brain, as well as with their memory brain, developing the competencies and tools they need to survive and succeed in our complex, interconnected society. One step toward this goal is to develop mathematical tasks that integrate subject-matter content with the context of application and that are aimed at preparing individuals for the world of work as well as for post-secondary education. Since many mathematics teachers have had limited workplace experience, they need many good examples of how knowledge of mathematics can be applied to real life situations. The trick in developing mathematical tasks for use in classrooms will be to keep the tasks connected to real life situations that the student will recognize. The tasks should not be just a contrived exercise but should stay as close to solving common problems as possible. As an example, why not ask students to compute the cost of 12 years of schooling in a public school? It is a sad irony that after 12 years of schooling most students who attend the public schools have no idea of the cost of their schooling or how their education was financed. No wonder that some public schools have difficulty gaining financial support! The individuals being served by the schools have never been exposed to the real life context of who pays for the schools and why. Somewhere along the line in the teaching of mathematics, this real life learning opportunity has been missed, along with many other similar contextual examples. The mathematical tasks in High School Mathematics at Work provide students (and teachers) with a plethora of real life mathematics problems and OCR for page 7 --> challenges to be faced in everyday life and work. The challenge for teachers will be to develop these tasks so they relate as close as possible to where students live and work every day. References Parnell, D. (1985). The neglected majority. Washington, DC: Community College Press. Parnell, D. (1995). Why do I have to learn this? Waco, TX: CORD Communications. Note 1. For further discussion of these issues, see Parnell (1985, 1995). DALE PARNELL is Professor Emeritus of the School of Education at Oregon State University. He has served as a University Professor, College President, and for ten years as the President and Chief Executive Officer of the American Association of Community Colleges. He has served as a consultant to the National Science Foundation and has served on many national commissions, such as the Secretary of Labor's Commission on Achieving Necessary Skills (SCANS). He is the author of the book The Neglected Majority which provided the foundation for the federally-funded Tech Prep Associate Degree Program. OCR for page 7 --> Almost any numerical claim may be treated as a Fermi question when the problem solver does not have access to all necessary background information. In such a situation, one may make rough guesses about relevant numbers, do a few calculations, and then produce estimates. Mathematical Analysis The examples are solved separately below. Grading Homework Although many component factors vary greatly from teacher to teacher or even from week to week, rough calculations are not hard to make. Some important factors to consider for the teacher are: how many classes he or she teaches, how many students are in each of the classes, how much experience has the teacher had in general and has the teacher previously taught the classes, and certainly, as part of teaching style, the kind of homework the teacher assigns, not to mention the teacher's efficiency in grading. Suppose the teacher has 5 classes averaging 25 students per class. Because the teacher plans to write corrections and comments, assume that the students' papers contain more than a list of answers—they show some student work and, perhaps, explain some of the solutions. Grading such papers might take as long as 10 minutes each, or perhaps even longer. Assuming that the teacher can grade them as quickly as 3 minutes each, on average, the teacher's grading time is: This is an impressively large number, especially for a teacher who already spends almost 25 hours/week in class, some additional time in preparation, and some time meeting with individual students. Is it reasonable to expect teachers to put in that kind of time? What compromises or other changes might the teacher make to reduce the amount of time? The calculation above offers four possibilities: Reduce the time spent on each homework paper, reduce the number of students per class, reduce the number of classes taught each day, or reduce the number of days per week that homework will be collected. If the teacher decides to spend at most 2 hours grading each night, what is the total number of students for which the teacher should have responsibility? This calculation is a partial reverse of the one above: If the teacher still has 5 classes, that would mean 8 students per class! The New York Times Answering this question requires two preliminary estimates: the circulation of The New York Times and the size of the newspaper. The answers will probably be different on Sundays. Though The New York Times is a national newspaper, the number of subscribers outside the New York metropolitan area is probably small compared to the number inside. The population of the New York metropolitan area is roughly ten million people. Since most families buy at most one copy, and not all families buy The New York Times, the circulation might be about 1 million newspapers each day. (A circulation of 500,000 seems too small and 2 million seems too big.) The Sunday and weekday editions probably have different OCR for page 7 --> circulations, but assume that they are the same since they probably differ by less than a factor of two—much less than an order of magnitude. When folded, a weekday edition of the paper measures about 1/2 inch thick, a little more than 1 foot long, and about 1 foot wide. A Sunday edition of the paper is the same width and length, but perhaps 2 inches thick. For a week, then, the papers would stack 6 × 1/2 + 2 = 5 inches thick, for a total volume of about 1 ft × 1 ft × 5/12 ft = 0.5 ft3. The whole circulation, then, would require about 1/2 million cubic feet of paper per week, or about 1 million cubic feet for a two-week supply. Is the company's warehouse big enough? The paper will come on rolls, but to make the estimates easy, assume it is stacked. If it were stacked 10 feet high, the supply would require 100,000 square feet of floor space. The company's 14,000 square foot storage facility will probably not be big enough as its size differs by almost an order of magnitude from the estimate. The circulation estimate and the size of the newspaper estimate should each be within a factor of 2, implying that the 100,000 square foot estimate is off by at most a factor of 4—less than an order of magnitude. How big a warehouse is needed? An acre is 43,560 square feet so about two acres of land is needed. Alternatively, a warehouse measuring 300 ft × 300 ft (the length of a football field in both directions) would contain 90,000 square feet of floor space, giving a rough idea of the size. Extensions After gaining some experience with these types of problems, students can be encouraged to pay close attention to the units and to be ready to make and support claims about the accuracy of their estimates. Paying attention to units and including units as algebraic quantities in calculations is a common technique in engineering and the sciences. Reasoning about a formula by paying attention only to the units is called dimensional analysis. Sometimes, rather than a single estimate, it is helpful to make estimates of upper and lower bounds. Such an approach reinforces the idea that an exact answer is not the goal. In many situations, students could first estimate upper and lower bounds, and then collect some real data to determine whether the answer lies between those bounds. In the traditional game of guessing the number of jelly beans in a jar, for example, all students should be able to estimate within an order of magnitude, or perhaps within a factor of two. Making the closest guess, however, involves some chance. Fermi questions are useful outside the workplace. Some Fermi questions have political ramifications: How many miles of streets are in your city or town? The police chief is considering increasing police presence so that every street is patrolled by car at least once every 4 hours. When will your town fill up its landfill? Is this a very urgent matter for the town's waste management personnel to assess in depth? In his 1997 State of the Union address, President Clinton renewed his call for a tax deduction of up to $10,000 for the cost of college tuition. He estimates that 16.5 million students stand to benefit. Is this a reasonable estimate of the number who might take advantage of the tax deduction? How much will the deduction cost in lost federal revenue? OCR for page 7 --> Creating Fermi problems is easy. Simply ask quantitative questions for which there is no practical way to determine exact values. Students could be encouraged to make up their own. Examples are: ''How many oak trees are there in Illinois?" or "How many people in the U.S. ate chicken for dinner last night?" "If all the people in the world were to jump in the ocean, how much would it raise the water level?" Give students the opportunity to develop their own Fermi problems and to share them with each other. It can stimulate some real mathematical thinking. OCR for page 7 --> Scheduling Elevators Task In some buildings, all of the elevators can travel to all of the floors, while in others the elevators are restricted to stopping only on certain floors. What is the advantage of having elevators that travel only to certain floors? When is this worth instituting? Commentary Scheduling elevators is a common example of an optimization problem that has applications in all aspects of business and industry. Optimal scheduling in general not only can save time and money, but it can contribute to safety (e.g., in the airline industry). The elevator problem further illustrates an important feature of many economic and political arguments—the dilemma of trying simultaneously to optimize several different needs. Politicians often promise policies that will be the least expensive, save the most lives, and be best for the environment. Think of flood control or occupational safety rules, for example. When we are lucky, we can perhaps find a strategy of least cost, a strategy that saves the most lives, or a strategy that damages the environment least. But these might not be the same strategies: generally one cannot simultaneously satisfy two or more independent optimization conditions. This is an important message for students to learn, in order to become better educated and more critical consumers and citizens. In the elevator problem, customer satisfaction can be emphasized by minimizing the average elevator time (waiting plus riding) for employees in an office building. Minimizing wait-time during rush hours means delivering many people quickly, which might be accomplished by filling the elevators and making few stops. During off-peak hours, however, minimizing wait-time means maximizing the availability of the elevators. There is no reason to believe that these two goals will yield the same strategy. Finding the best strategy for each is a mathematical problem; choosing one of the two strategies or a compromise strategy is a management decision, not a mathematical deduction. This example serves to introduce a complex topic whose analysis is well within the range of high school students. Though the calculations require little more than arithmetic, the task puts a premium on the creation of reasonable alternative strategies. Students should recognize that some configurations (e.g., all but one elevator going to the top floor and the one going to all the others) do not merit consideration, while others are plausible. A systematic evaluation of all possible configurations is usually required to find the optimal solution. Such a systematic search of the possible solution space is important in many modeling situations where a formal optimal strategy is not known. Creating and evaluating reasonable strategies for the elevators is quite appropriate for high school student mathematics and lends itself well to thoughtful group effort. How do you invent new strategies? How do you know that you have considered all plausible strategies? These are mathematical questions, and they are especially amenable to group discussion. Students should be able to use the techniques first developed in solving a simple case with only a few stories and a few elevators to address more realistic situations (e.g., 50 stories, five elevators). Using the results of a similar but simpler problem to model a more complicated problem is an important way to reason in mathematics. Students OCR for page 7 --> need to determine what data and variables are relevant. Start by establishing the kind of building—a hotel, an office building, an apartment building? How many people are on the different floors? What are their normal destinations (e.g., primarily the ground floor or, perhaps, a roof-top restaurant). What happens during rush hours? To be successful at the elevator task, students must first develop a mathematical model of the problem. The model might be a graphical representation for each elevator, with time on the horizontal axis and the floors represented on the vertical axis, or a tabular representation indicating the time spent on each floor. Students must identify the pertinent variables and make simplifying assumptions about which of the possible floors an elevator will visit. Mathematical Analysis This section works through some of the details in a particularly simple case. Consider an office building with six occupied floors, employing 240 people, and a ground floor that is not used for business. Suppose there are three elevators, each of which can hold 10 people. Further suppose that each elevator takes approximately 25 seconds to fill on the ground floor, then takes 5 seconds to move between floors and 15 seconds to open and close at each floor on which it stops. Scenario One What happens in the morning when everyone arrives for work? Assume that everyone arrives at approximately the same time and enters the elevators on the ground floor. If all elevators go to all floors and if the 240 people are evenly divided among all three elevators, each elevator will have to make 8 trips of 10 people each. When considering a single trip of one elevator, assume for simplicity that 10 people get on the elevator at the ground floor and that it stops at each floor on the way up, because there may be an occupant heading to each floor. Adding 5 seconds to move to each floor and 15 seconds to stop yields 20 seconds for each of the six floors. On the way down, since no one is being picked up or let off, the elevator does not stop, taking 5 seconds for each of six floors for a total of 30 seconds. This round-trip is represented in Table 1. TABLE 1: Elevator round-trip time, Scenario one TIME (SEC) Ground Floor 25 Floor 1 20 Floor 2 20 Floor 3 20 Floor 4 20 Floor 5 20 Floor 6 20 Return 30 ROUND-TRIP 175 Since each elevator makes 8 trips, the total time will be 1,400 seconds or 23 minutes, 20 seconds. Scenario Two Now suppose that one elevator serves floors 1–3 and, because of the longer trip, two elevators are assigned to floors 4–6. The elevators serving the top OCR for page 7 --> TABLE 2: Elevator round-trip times, Scenario two ELEVATOR A ELEVATORS B & C Stop Time STOP TIME Ground Floor 25 25 Floor 1 1 20 5 Floor 2 2 20 5 Floor 3 3 20 5 Floor 4 0 4 20 Floor 5 0 5 20 Floor 6 0 6 20 Return 15 30 ROUND-TRIP 100 130 floors will save 15 seconds for each of floors 1–3 by not stopping. The elevator serving the bottom floors will save 20 seconds for each of the top floors and will save time on the return trip as well. The times for these trips are shown in Table 2. Assuming the employees are evenly distributed among the floors (40 people per floor), elevator A will transport 120 people, requiring 12 trips, and elevators B and C will transport 120 people, requiring 6 trips each. These trips will take 1200 seconds (20 minutes) for elevator A and 780 seconds (13 minutes) for elevators B and C, resulting in a small time savings (about 3 minutes) over the first scenario. Because elevators B and C are finished so much sooner than elevator A, there is likely a more efficient solution. Scenario Three The two round-trip times in Table 2 do not differ by much because the elevators move quickly between floors but stop at floors relatively slowly. This observation suggests that a more efficient arrangement might be to assign each elevator to a pair of floors. The times for such a scenario are listed in Table 3. Again assuming 40 employees per floor, each elevator will deliver 80 people, requiring 8 trips, taking at most a total of 920 seconds. Thus this assignment of elevators results in a time savings of almost 35% when compared with the 1400 seconds it would take to deliver all employees via unassigned elevators. TABLE 3: Elevator round-trip times, Scenario three ELEVATOR A ELEVATOR B ELEVATOR C STOP TIME STOP TIME STOP TIME Ground Floor 25 25 25 Floor 1 1 20 5 5 Floor 2 2 20 5 5 Floor 3 0 3 20 5 Floor 4 0 4 20 5 Floor 5 0 0 5 20 Floor 6 0 0 6 20 Return 10 20 30 ROUND-TRIP 75 95 115 OCR for page 7 --> Perhaps this is the optimal solution. If so, then the above analysis of this simple case suggests two hypotheses: The optimal solution assigns each floor to a single elevator. If the time for stopping is sufficiently larger than the time for moving between floors, each elevator should serve the same number of floors. Mathematically, one could try to show that this solution is optimal by trying all possible elevator assignments or by carefully reasoning, perhaps by showing that the above hypotheses are correct. Practically, however, it doesn't matter because this solution considers only the morning rush hour and ignores periods of low use. The assignment is clearly not optimal during periods of low use, and much of the inefficiency is related to the first hypothesis for rush hour optimization: that each floor is served by a single elevator. With this condition, if an employee on floor 6 arrives at the ground floor just after elevator C has departed, for example, she or he will have to wait nearly two minutes for elevator C to return, even if elevators A and B are idle. There are other inefficiencies that are not considered by focusing on the rush hour. Because each floor is served by a single elevator, an employee who wishes to travel from floor 3 to floor 6, for example, must go via the ground floor and switch elevators. Most employees would prefer more flexibility than a single elevator serving each floor. At times when the elevators are not all busy, unassigned elevators will provide the quickest response and the greatest flexibility. Because this optimal solution conflicts with the optimal rush hour solution, some compromise is necessary. In this simple case, perhaps elevator A could serve all floors, elevator B could serve floors 1-3, and elevator C could serve floors 4-6. The second hypothesis, above, deserves some further thought. The efficiency of the rush hour solution Table 3 is due in part to the even division of employees among the floors. If employees were unevenly distributed with, say, 120 of the 240 people working on the top two floors, then elevator C would need to make 12 trips, taking a total of 1380 seconds, resulting in almost no benefit over unassigned elevators. Thus, an efficient solution in an actual building must take into account the distribution of the employees among the floors. Because the stopping time on each floor is three times as large as the traveling time between floors (15 seconds versus 5 seconds), this solution effectively ignores the traveling time by assigning the same number of employees to each elevator. For taller buildings, the traveling time will become more significant. In those cases fewer employees should be assigned to the elevators that serve the upper floors than are assigned to the elevators that serve the lower floors. Extensions The problem can be made more challenging by altering the number of elevators, the number of floors, and the number of individuals working on each floor. The rate of movement of elevators can be determined by observing buildings in the local area. Some elevators move more quickly than others. Entrance and exit times could also be measured by students collecting OCR for page 7 --> data on local elevators. In a similar manner, the number of workers, elevators, and floors could be taken from local contexts. A related question is, where should the elevators go when not in use? Is it best for them to return to the ground floor? Should they remain where they were last sent? Should they distribute themselves evenly among the floors? Or should they go to floors of anticipated heavy traffic? The answers will depend on the nature of the building and the time of day. Without analysis, it will not be at all clear which strategy is best under specific conditions. In some buildings, the elevators are controlled by computer programs that "learn" and then anticipate the traffic patterns in the building. A different example that students can easily explore in detail is the problem of situating a fire station or an emergency room in a city. Here the key issue concerns travel times to the region being served, with conflicting optimization goals: average time vs. maximum time. A location that minimizes the maximum time of response may not produce the least average time of response. Commuters often face similar choices in selecting routes to work. They may want to minimize the average time, the maximum time, or perhaps the variance, so that their departure and arrival times are more predictable. Most of the optimization conditions discussed so far have been expressed in units of time. Sometimes, however, two optimization conditions yield strategies whose outcomes are expressed in different (and sometimes incompatible) units of measurement. In many public policy issues (e.g., health insurance) the units are lives and money. For environmental issues, sometimes the units themselves are difficult to identify (e.g., quality of life). When one of the units is money, it is easy to find expensive strategies but impossible to find ones that have virtually no cost. In some situations, such as airline safety, which balances lives versus dollars, there is no strategy that minimize lives lost (since additional dollars always produce slight increases in safety), and the strategy that minimizes dollars will be at $0. Clearly some compromise is necessary. Working with models of different solutions can help students understand the consequences of some of the compromises. OCR for page 7 --> Heating-Degree-Days Task An energy consulting firm that recommends and installs insulation and similar energy saving devices has received a complaint from a customer. Last summer she paid $540 to insulate her attic on the prediction that it would save 10% on her natural gas bills. Her gas bills have been higher than the previous winter, however, and now she wants a refund on the cost of the insulation. She admits that this winter has been colder than the last, but she had expected still to see some savings. The facts: This winter the customer has used 1,102 therms, whereas last winter she used only 1,054 therms. This winter has been colder: 5,101 heating-degree-days this winter compared to 4,201 heating-degree-days last winter. (See explanation below.) How does a representative of the energy consulting firm explain to this customer that the accumulated heating-degree-days measure how much colder this winter has been, and then explain how to calculate her anticipated versus her actual savings. Commentary Explaining the mathematics behind a situation can be challenging and requires a real knowledge of the context, the procedures, and the underlying mathematical concepts. Such communication of mathematical ideas is a powerful learning device for students of mathematics as well as an important skill for the workplace. Though the procedure for this problem involves only proportions, a thorough explanation of the mathematics behind the procedure requires understanding of linear modeling and related algebraic reasoning, accumulation and other precursors of calculus, as well as an understanding of energy usage in home heating. Mathematical Analysis The customer seems to understand that a straight comparison of gas usage does not take into account the added costs of colder weather, which can be significant. But before calculating any anticipated or actual savings, the customer needs some understanding of heating-degree-days. For many years, weather services and oil and gas companies have been using heating-degree-days to explain and predict energy usage and to measure energy savings of insulation and other devices. Similar degree-day units are also used in studying insect populations and crop growth. The concept provides a simple measure of the accumulated amount of cold or warm weather over time. In the discussion that follows, all temperatures are given in degrees Fahrenheit, although the process is equally workable using degrees Celsius. Suppose, for example, that the minimum temperature in a city on a given day is 52 degrees and the maximum temperature is 64 degrees. The average temperature for the day is then taken to be 58 degrees. Subtracting that result from 65 degrees (the cutoff point for heating), yields 7 heating-degree-days for the day. By recording high and low temperatures and computing their average each day, heating-degree-days can be accumulated over the course of a month, a winter, or any period of time as a measure of the coldness of that period. Over five consecutive days, for example, if the average temperatures were 58, 50, 60, 67, and 56 degrees Fahrenheit, the calculation yields 7, 15, 5, 0, and 9 heating-degree-days respectively, for a total accumulation of 36 heating-degree-days for the five days. Note that the fourth day contributes 0 heating-degree-days to the total because the temperature was above 65 degrees. OCR for page 7 --> The relationship between average temperatures and heating-degree-days is represented graphically in Figure 1. The average temperatures are shown along the solid line graph. The area of each shaded rectangle represents the number of heating-degree-days for that day, because the width of each rectangle is one day and the height of each rectangle is the number of degrees below 65 degrees. Over time, the sum of the areas of the rectangles represents the number of heating-degree-days accumulated during the period. (Teachers of calculus will recognize connections between these ideas and integral calculus.) The statement that accumulated heating-degree-days should be proportional to gas or heating oil usage is based primarily on two assumptions: first, on a day for which the average temperature is above 65 degrees, no heating should be required, and therefore there should be no gas or heating oil usage; second, a day for which the average temperature is 25 degrees (40 heating-degree-days) should require twice as much heating as a day for which the average temperature is 45 FIGURE 1: Daily heating-degree-days degrees (20 heating-degree-days) because there is twice the temperature difference from the 65 degree cutoff. The first assumption is reasonable because most people would not turn on their heat if the temperature outside is above 65 degrees. The second assumption is consistent with Newton's law of cooling, which states that the rate at which an object cools is proportional to the difference in temperature between the object and its environment. That is, a house which is 40 degrees warmer than its environment will cool at twice the rate (and therefore consume energy at twice the rate to keep warm) of a house which is 20 degrees warmer than its environment. The customer who accepts the heating-degree-day model as a measure of energy usage can compare this winter's usage with that of last winter. Because 5,101/4,201 = 1.21, this winter has been 21% colder than last winter, and therefore each house should require 21% more heat than last winter. If this customer hadn't installed the insulation, she would have required 21% more heat than last year, or about 1,275 therms. Instead, she has required only 5% more heat (1,102/1,054 = 1.05), yielding a savings of 14% off what would have been required (1,102/1,275 = .86). Another approach to this would be to note that last year the customer used 1,054 therms/4,201 heating-degree-days = .251 therms/heating-degree-day, whereas this year she has used 1,102 therms/5,101 heating-degree-days = .216 therms/heating-degree-day, a savings of 14%, as before. OCR for page 7 --> Extensions How good is the heating-degree-day model in predicting energy usage? In a home that has a thermometer and a gas meter or a gauge on a tank, students could record daily data for gas usage and high and low temperature to test the accuracy of the model. Data collection would require only a few minutes per day for students using an electronic indoor/outdoor thermometer that tracks high and low temperatures. Of course, gas used for cooking and heating water needs to be taken into account. For homes in which the gas tank has no gauge or doesn't provide accurate enough data, a similar experiment could be performed relating accumulated heating-degree-days to gas or oil usage between fill-ups. It turns out that in well-sealed modern houses, the cutoff temperature for heating can be lower than 65 degrees (sometimes as low as 55 degrees) because of heat generated by light bulbs, appliances, cooking, people, and pets. At temperatures sufficiently below the cutoff, linearity turns out to be a good assumption. Linear regression on the daily usage data (collected as suggested above) ought to find an equation something like U = -.251(T - 65), where T is the average temperature and U is the gas usage. Note that the slope, -.251, is the gas usage per heating-degree-day, and 65 is the cutoff. Note also that the accumulation of heating-degree-days takes a linear equation and turns it into a proportion. There are some important data analysis issues that could be addressed by such an investigation. It is sometimes dangerous, for example, to assume linearity with only a few data points, yet this widely used model essentially assumes linearity from only one data point, the other point having coordinates of 65 degrees, 0 gas usage. Over what range of temperatures, if any, is this a reasonable assumption? Is the standard method of computing average temperature a good method? If, for example, a day is mostly near 20 degrees but warms up to 50 degrees for a short time in the afternoon, is 35 heating-degree-days a good measure of the heating required that day? Computing averages of functions over time is a standard problem that can be solved with integral calculus. With knowledge of typical and extreme rates of temperature change, this could become a calculus problem or a problem for approximate solution by graphical methods without calculus, providing background experience for some of the important ideas in calculus. Students could also investigate actual savings after insulating a home in their school district. A customer might typically see 8-10% savings for insulating roofs, although if the house is framed so that the walls act like chimneys, ducting air from the house and the basement into the attic, there might be very little savings. Eliminating significant leaks, on the other hand, can yield savings of as much as 25%. Some U.S. Department of Energy studies discuss the relationship between heating-degree-days and performance and find the cutoff temperature to be lower in some modern houses. State energy offices also have useful documents. What is the relationship between heating-degree-days computed using degrees Fahrenheit, as above, and heating-degree-days computed using degrees Celsius? Showing that the proper conversion is a direct proportion and not the standard Fahrenheit-Celsius conversion formula requires some careful and sophisticated mathematical thinking.
Find a West Bridgewater SATDespite its seminal importance in the modern world, calculus introduces only one truly new concept: the limit. The other two major tools of calculus - differentiation and integration - are simply application of the limit to different kinds of problems. Mastering calculus requires a strong foundation of algebra and trigonometry, followed by an in-depth understanding of limits.
Introduction to Proof in Abstract Mathematics Introduction to Proof in Abstract Mathematics The primary purpose of this undergraduate text is to teach students to do mathematical proofs. It enables readers to recognize the elements that constitute an acceptable proof, and it develops their ability to do proofs of routine problems as well as those requiring creative insights. The self-contained treatment features many exercises, problems, and selected answers, including worked-out solutions. Starting with sets and rules of inference, this text covers functions, relations, operation, and the integers. Additional topics include proofs in analysis, cardinality, and groups. Six appendixes offer supplemental material. Teachers will welcome the return of this long-out-of-print volume, appropriate for both one- and two-semester courses. Reprint of the Saunders College Publishing, Philadelphia, 1990 edition.
More About This Textbook Overview Undergraduates in engineering and the physical sciences receive a thorough introduction to perturbation theory in this useful and accessible text. Students discover methods for obtaining an approximate solution of a mathematical problem by exploiting the presence of a small, dimensionless parameter — the smaller the parameter, the more accurate the approximate solution. Knowledge of perturbation theory offers a twofold benefit: approximate solutions often reveal the exact solution's essential dependence on specified parameters; also, some problems resistant to numerical solutions may yield to perturbation methods. In fact, numerical and perturbation methods can be combined in a complementary way. The text opens with a well-defined treatment of finding the roots of polynomials whose coefficients contain a small parameter. Proceeding to differential equations, the authors explain many techniques for handling perturbations that reorder the equations or involve an unbounded independent variable. Two disparate practical problems that can be solved efficiently with perturbation methods conclude the volume. Written in an informal style that moves from specific examples to general principles, this elementary text emphasizes the "why" along with the "how"; prerequisites include a knowledge of one-variable calculus and ordinary differential equations. This newly revised second edition features an additional appendix concerning the approximate evaluation of integrals
More About This Textbook Overview "Math Principals for Food Service Occupations, 4th Edition" teaches students that the understanding and application of mathematics is critical for all food service jobs, from a salad person to an executive chef. All the mathematics problems and concepts presented are done so in a simplified, logical, step-by-step manner. In this 4th edition, "Chef Sez", quotes from chefs and managers, have been added to show students just how applicable these skills are to food service professionals. TIPS - To Insure Perfect Solutions - have been included to provide hints on how to make problem solving simple. Learning objectives have also been added at the beginning of each chapter to identify the key information to be learned. The content, including the answer key in the Instructor's Manual, has been completely revised to ensure accuracy and relevancy. Related Subjects Meet the Author Anthony J. Strianese is a professor for and chairperson of the Department of Hotel, Culinary Arts and Tourism at Schenectady County Community College in Schenectady, New York. In 1998, he was presented with the State University of New York Chancellor's Award for Excellence in Administrative Services. Mr. Strianese holds a Master of Science degree in Educational Psychology from the College of Saint Rose in Albany, New York and a Bachelor of Science degree in Business Administration from Bryant College in Smithfield, Rhode Island. Mr. Strianese is a Certified Culinary Educator (CCE) and is a national evaluator for the American Culinary Federation Educational Institute. He is Food and Beverage Controller at the Downtowner Motor Inn in Albany, New York, Banquet Manager at the DeWitt Clinton Hotel in Albany, New York and is a Walt Disney World Coordinator. He also serves as an officer of Silent Butler Catering in Clifton Park, New York. Mr. Strianese is co-chairperson of the Education Committee of the New York State Hospitality and Tourism Association. He is also co-chairperson of the Albany County Convention and Visitors Bureau. He serves as a judge for the NYSH&TA STARS of the Industry and as a judge for New York State Restaurant Association Outstanding employees. Mr. Strianese is a member of the American Culinary Federation (ACF), the Council on Hotel, Restaurant Institutional Education (CHRIE) and the National Restaurant Association (NRA). Pamela P. Strianese is a teacher for North Colonie Central Schools in Loudonville, New York. She holds a Master of Science in Education from the State University of New York at Albany and a Bachelor of Arts in Education from the State University of New York at Fredonia. She has served on numerous committees for curriculum development. Ms. Strianese is the former treasurer of Silent Butler Catering in Clifton Park, New York, former catering assistant of Selma's Catering in Schenectady, New York and former bookkeeper for Union Coach House Restaurant in Saratoga, New York. She is a member of the Albany Area Reading
More About This Textbook Editorial Reviews Children's Literature - Amie Rose Rotruck When they first begin to study mathematics, few students think about the origins of the principles they are learning. However, there is a rich history of the development of math spanning thousands of years. In this title from the "Pioneers in Mathematics" series, Bradley examines the major contributors to mathematics that lived between 1300 and 1800 AD, including John Napier, Blaise Pascal, Sir Isaac Newton, and Leohnhard Euler. Women and minorities are not often well represented in the math books, but Bradely makes a point to include Maria Agnesi, an Italian woman, and Benjamin Banneker, a freed slave whose mathematical theories were published in the late eighteenth century in the United States. Every mathematician mentioned has their own chapter, which includes a description of their lives and a thorough but easily digested explanation of the mathematical principles they developed. In addition to diagrams illustrating the mathematics when required, there are numerous pictures to offer a more thorough look at the lives of these mathematicians. An excellent resource to bring life to math, as well as a useful tool when researching any of the mathematicians. VOYA - Sarah Flowers This five-volume set explores the lives and contributions of fifty people who made major developments in mathematics, from ancient times to the present. The second volume, The Age of Geniuis, covers the years from 1300 to 1800 and includes giants of the field such as Newton, Leibniz, Pascal, and Fermat. All volumes include women and non-Westerners, giving the series a broad coverage of the history of mathematics worldwide. In addition, the chosen mathematicians well illustrate the relationship of mathematics to other sciences, especially astronomy, physics, and computer science. Some knowledge of algebra and geometry is helpful in reading the details of each mathematician's contributions, but illustrations and diagrams abound to assist in comprehension. Glossaries, lists of further reading, and pronunciation guides add to the usefulness of the volumes. Other series entries include The The Age of Geniuis: 1300-1800, The Foundations of Mathematics: 1800-1900, Modern Mathematics: 1900-1950, and Mathematics Frontiers: 1950
The Humongous Book of Basic Math and Pre-Algebra Problems Book Description: Soon math problems will be no problem at all... Most math and study guides are as dry and difficult as the professors that write them. In The Humongous Book of Basic Math and Pre-Algebra Problems, author W. Michael Kelley enjoys being the exception. It is full of solved problems, but along the margin Kelley makes notes, adding missing steps and simplifying concepts. In this way questions that would normally baffle students suddenly become crystal clear. His unique method fully prepares students to solve those difficult, obscure problems that were never covered in class but always seem to find their way onto exams. • Annotated notes throughout the book to clarify each problem • An expert author on the topic with a great track record for helping students and math enthusiasts • Author's website calculus-help.com reaches thousands of students every month
A Textbook of Engineering Mathematics (Volume II) is a comprehensive text for the students of engineering Key features Each topic is treated in a systematic and logical manner Incorporates a large number of solved and unsolved problems for each topic Elucidates all basic concepts with the aid of pedagogical features such as Introduction, Definitions Includes question papers from previous years U.P.T.U. examinations. Several Worked out examples drawn from various examination papers of reupted Universities, as well as I.A.S., P.C.S. competitions. An exhaustive list of "objective type of questions" fill in the blanks and matching the answers type of problems are also provided at the end of each chapter. With a unique step-by-step approach and real-life business-based examples throughout, CONTEMPORARY MATHEMATICS FOR BUSINESS AND CONSUMERS, Fifth Edition, is designed to help students overcome math anxiety and confidently master key mathematical concepts and their practical business applications. This volume addresses the key issue of the initial education and lifelong professional learning of teachers of mathematics to enable them to realize the affordances of educational technology for mathematics. With invited contributions from leading scholars in the field, this volume contains a blend of research articles and descriptive texts. Mathematics curriculum, which is often a focus in education reforms, has not received extensive research attention until recently. Ongoing mathematics curriculum changes in many education systems call for further research and sharing of effective curriculum policies and practices that can help lead to the improvement of school education. This is a textbook for an introductory graduate course on partial differential equations. Han focuses on linear equations of first and second order. An important feature of his treatment is that the majority of the techniques are applicable more generally. Differential Galois theory has seen intense research activity during the last decades in several directions: elaboration of more general theories, computational aspects, model theoretic approaches, applications to classical and quantum mechanics as well as to other mathematical areas such as number theory. Handbook on the History of Mathematics Education ( Ryushare - Rapidgator ) This is the first comprehensive International Handbook on the History of Mathematics Education, covering a wide spectrum of epochs and civilizations, countries and cultures. Until now, much of the research into the rich and varied history of mathematics education has remained inaccessible to the vast majority of scholars, not least because it has been written in the language, and for readers, of an individual country.
An online course: learning units presented in worksheet format review the most important results, techniques and formulas in college and pre-college calculus. Logarithms and Exponential; Sequences; Series; Techniques of... This field guide contains a quick look at the functions commonly encountered in single variable calculus, with exercises for each topic: linear, polynomial, power, rational, exponential, logarithmic, trigonometricA unit that addresses the sheer volume of incomprehensible numbers (speed, distance, age) in the natural world, helping students to understand the scale of the world using the concepts of rates, proportions and...
Elementary Statistics - With CD (High School) - 2nd edition Summary: For algebra-based Introductory Statistics courses. Elementary Statistics teams the proven authorship and pedagogical expertise of Larson with Farber's 30 years of statistics-teaching experience. It will appeal to today's visually oriented and more technologically savvy students. Highlights Graphical Approach that incorporates the graphical display of data throughout. Flexible tec...show morehnology--Introduces each new technique with hand calculations before a worked-out Technology Example is presented. More than 1,700 exercises--Includes a wide variety in each section that moves from basic concepts and skill development to more challenging problems. Titled examples paired with unique Try It Yourself problems--Illustrates every concept in the text with step-by-step examples numbered and titled for easy reference, Immediately followed with a similar problem. "Real Statistics, Real Decisions" challenges students to make decisions about which techniques to use.3.99 +$3.99 s/h Acceptable Borgasorus Books, Inc. MO Wentzville, MO Hardcover Fair 01304888526.05 32E $6.49 +$3.99 s/h Acceptable AlphaBookWorks Alpharetta, GA 0130488852100
1. To obtain an accurate view of the mathematical concepts demanded by the elementary mathematics curriculum and how students can learn them. 2. To appreciate and understand both the historical developments and the current applications of mathematics. 3. To gain an understanding and appreciation of the National Council of Teachers of Mathematics (NCTM) curriculum standards: • learn to value mathematics • become confident in one's ability to do mathematics • become a mathematical problem solver • learn to communicate mathematically • learn to reason mathematically 4. To be prepared to teach mathematics in accordance with the NCTM standards4. Computer Technology: Elements of programming in BASIC and LOGO, computer software for geometrical explorations and an introduction to graphics calculators. 5. Equivalence Relations 6. Clock Arithmetic VII. Methods of Instruction The classroom component of this course will feature lectures on the primary topics high-lighted in the outline of topics. The course will emphasize student participation through individual and group activities, cooperative learning techniques, and problem solving activities. Use of calculators, computers, and videos will be an integral part of the course. Course may be taught as face-to-face, media-based, hybrid or online course. VIII. Course Practices Required Complete assigned readings and homework and attend and participate in all scheduled class lectures and class discussions. IX. Instructional Materials Note: Current textbook information for each course and section is available on Oakton's Schedule of Classes. Textbook information for each course and section is available on Oakton's Schedule of Classes. Within the Schedule of Classes, textbooks can be found by clicking on an individual course section and looking for the words "View Book Information". Textbooks can also be found at our Mathematics Textbooks page. A scientific calculator, notebook, and earphones are required. X. Methods of Evaluating Student Progress Evaluation will include class projects, homework, quizzes, tests and a final examination
Through lecture, discussion, and collaborative projects, students will explore some of the basic areas of mathematics including sets, logic, probability, statistics, and mathematical systems. Emphasis will be placed on problem-solving throughout the course and real world examples will be used insofar as possible.
Algebra Do your students attempt to memorize facts and mimic examples to make it through algebra? James Stewart, author of the worldwide, best-selling ...Show synopsisDo your students attempt to memorize facts and mimic examples to make it through algebra? James Stewart, author of the worldwide, best-selling calculus texts, saw this scenario time and again in his classes. So, along with longtime coauthors Lothar Redlin and Saleem Watson, he wrote "College Algebra, 6/e, International Edition" specifically to help students learn to think mathematically and to develop genuine problem-solving skills. Comprehensive and evenly-paced, the text has helped hundreds of thousands of students. Incorporating technology, real-world applications, and additional useful pedagogy, the sixth edition promises to help more students than ever build conceptual understanding and a core of fundamental skills.Hide synopsis Description:Good. 073 Item may show signs of shelf wear. Pages may include...Good. 073 686 p. Contains: Illustrations, color, Figures
Maths A-Level Develop their understanding of mathematics and mathematical processes in a way that promotes confidence and fosters enjoyment Develop abilities to reason logically and to recognise incorrect reasoning, to generalise and to construct mathematical proofs Extend their range of mathematical skills and techniques and use them in more difficult unstructured problems Develop an understanding of coherence and progression in mathematics and of how different areas of mathematics can be connected Recognise how a situation may be represented mathematically and understand the relationship between 'real world' problems and standard and other mathematical models, and how these can be refined and improved Acquire the skills needed to use technology such as calculators and computers effectively, to recognise when such use may be inappropriate and to be aware of limitations Who Should Study This Course? This course is very demanding and requires a high level of understanding at GCSE level. Students who undertake this course are usually those who wish to study mathematics or sciences at University level. Why Should I study This Course? Success in Mathematics indicates an individual's ability to: Solve problems Develop sound reasoning skills Develop an analytical mind Think laterally Develop higher level thinking skills Be organised and keep to schedules For most Maths students it is their main subject or supports a Science. Others study Maths because it is a very different academic subject.
Word Problems: No Problem! Having a problem with word problems? Author Rebecca Wingard-Nelson introduces simple ways to tackle tricky word problems with algebra. Real world ...Show synopsisHaving a problem with word problems? Author Rebecca Wingard-Nelson introduces simple ways to tackle tricky word problems with algebra. Real world examples make the book easy to read and are great for students to use on their own, or with parents, teachers, or tutors. Free downloadable worksheets are available on Having a problem with word problems? Author Rebecca...New. Having a problem with word problems? Author Rebecca Wingard-Nelson introduces simple ways to tackle tricky word problems with algebra. Real world examples make the book easy to read and are great for students to use on their own, or with parents, tea
Intermediate Algebra - 3rd edition Summary: KEY BENEFIT:Intermediate Algebra, Third Edition, by Tom Carson, addresses two fundamental issues-individual learning styles and student comprehension of key mathematical concepts-to meet the needs of today's students and instructors.Carson's Study System, presented in the ldquo;To the Studentrdquo; section at the front of the text, adapts to the way each student learns to ensure their success in this and future courses. The consistent emphasis on thebig picture of algebra, with pedag...show moreogy and support that helps students put each new concept into proper context, encourages conceptual understanding. KEY TOPICS: Real Numbers and Expressions; Linear Equations and Inequalities in One Variable; Equations and Inequalities in Two Variables and Functions; Systems of Linear Equations and Inequalities; Exponents, Polynomials, and Polynomial Functions; Factoring; Rational Expressions and Equations; Rational Exponents, Radicals, and Complex Numbers; Quadratic Equations and Functions; Exponential and Logarithmic Functions; Conic Sections MARKET: For all readers interested in algebra1607112 Item in very good condition and at a great price!40.5459.99 +$3.99 s/h New BookStore101 SUNNY ISLES BEACH, FL INSTRUCTOR EDITION.ALL ANSWERS INCLUDED.CD IS INCLUDED.Identical to student edition.Black tape on cover. NOT ACCESS CODE.SHIPS FAST!! SAME DAY OR W/N 24 HOURS.EXPEDITED SHIPPING AVAILABLE TOO!! $72.10 +$3.99 s/h New Textbookcenter.com Columbia, MO Ships same day or next business day! UPS(AK/HI Priority Mail)/ NEW book $123.15166
Search ResultsThis is a resource book for mathematics teachers for use in Y9, Y10 and Y11. Its aims are twofold: first, to provide a vehicle for covering much of the National Curriculum through applications of mathematics to real-life problems; second, to provide a resource which can be used for the courseworkCambridge French is a five year programme designed to make the study of a foreign language exciting and stimulating, and to provide students with an enjoyable experience of the French language. Using materials appropriate to their interests, growing maturity and linguistic attainment, the course…
Videos Will Help Students "Ace" Math 02/01/97 Ace-Math, an award-winning video tutorial series, is suited for students trying to grasp fundamental mathematical concepts, parents who want to help their child with their homework, or people who need to brush up on math skills for a specialized license or test. There are nine separate series, each with many individual videos: Basic Mathematical Skills, Pre-Algebra, Algebra I, Algebra II, Advanced Algebra, Trigonometry, Calculus, Geometry, and Probability and Statistics. Each series except Algebra I consists of 30-minute videotapes explaining various concepts. Algebra I has 16 hour-long videos. For only $29.95, Ace-Math purchasers get a 30-minute tape with the right to make two back-up copies. This lets educators keep the tape in the learning center and let students check out a copy to take home -- with the added security of another back-up copy! These innovative tapes have been purchased by institutions such as NASA, the U.S. Coast Guard and IBM, and are in use at institutions such as the Los Angeles Public Library and New York Public Library.Video Resources Software, Miami, FL, (888) ACE-MATH
9780750303 Polynomials to Sums of Squares From Polynomials to Sums of Squares describes a journey through the foothills of algebra and number theory based around the central theme of factorization. The book begins by providing basic knowledge of rational polynomials, then gradually introduces other integral domains, and eventually arrives at sums of squares of integers. The text is complemented with illustrations that feature specific examples. Other than familiarity with complex numbers and some elementary number theory, very little mathematical prerequisites are needed. The accompanying disk enables readers to explore the subject further by removing the tedium of doing calculations by hand. Throughout the text there are practical activities involving the computer
Mathematics Meets Technology - Brian Bolt - Paperback 9780521376921 ISBN: 0521376920 Publisher: Cambridge University Press Summary: A resource book which looks at the design of mechanisms, for example gears and linkages, through the eyes of a mathematician. Readers are encouraged to make models throughout and to look for further examples in everyday life. Suitable for GCSE, A level, and mathematics/technology/engineering courses in Further Education. Bolt, Brian is the author of Mathematics Meets Technology - Brian Bolt - Paperback, publ...ished under ISBN 9780521376921 and 0521376920. Nine hundred three Mathematics Meets Technology - Brian Bolt - Paperback textbooks are available for sale on ValoreBooks.com, three hundred two used from the cheapest price of $3.53, or buy new starting at $26.61.[read more]
Don't expect to learn anything if you have him for Stats. As a student, I had to correct his mistakes (which of course lowers your grade). If you're good at math, you should be ok. If you have no idea about stats, stay away. You have to buy the book. He grades HW for correctness, not completion.
Compressed Zip File Be sure that you have an application to open this file type before downloading and/or purchasing. How to unzip files. 1.73 MB | 11 pages PRODUCT DESCRIPTION This lesson is intended for AP Calculus AB students, but can be used in CALCULUS HONORS or PRECALCULUS courses. The single lesson includes a student handout, a SMARTNOTEBOOK 11 presentation, and a completed set of notes for the lesson. Students will understand continuity at a point, properties of continuity, the existence of a limit, the definition of continuity on a closed interval, classifying discontinuities as removable or non-removable, and find values to create a continuous function. Comments & Ratings Product Questions & Answers Be the first to ask Jean Adams70.
This book is a carefully written exposition of Coxeter groups, an area of mathematics which appears in algebra, geometry, and combinatorics. In this book, the combinatorics of Coxeter groups has mainly to do with reduced expressions, partial order of group elements, enumeration, associated graphs and combinatorial cell complexes, and more. more...
Editorial Reviews Booknews Focusing on a limited number of topics in more depth than is perhaps customary in a calculus text, this volume emphasizes the meaning, in practical, graphical, and numerical terms, of the symbols used. Chapters cover functions, the derivative and the definite integral, short-cuts to differentiation, using the derivative, constructive antiderivatives, integration, using the definite integral, approximations and series, differential equations, functions of several variables, vectors, differentiating functions of many variables, optimization, integrating functions of many variables, parameterized curves, vector fields, line integrals, flux integrals, and calculus of vector fields. Includes short answers to odd-numbered problems at the back of the book
Intensive study of the problem-solving process. Algebraic, patterning, modeling and geometric strategies are explored. Includes a review of basic algebra skills and concepts necessary for problem solving. Consent of the Department is required. This does not fulfill the College Ge... This course studies polynomial, rational, exponential, logarithmic, and trigonometric functions from the symbolic, numeric, and graphical perspectives. The emphasis on these concepts will provide solid preparation for a college-level calculus course. Introduction to differential and integral calculus designed primarily for liberal arts students and those in the professional programs. Limits are treated intuitively. Emphasis on applications. MATH 105 is prerequisite for MATH 106. Introduction to differential and integral calculus designed primarily for liberal arts students and those in the professional programs. Limits are treated intuitively. Emphasis on applications. MATH 105 is prerequisite for MATH 106.
10+ subjects including calculus
Demystified Unlike most books on algebra, this guide lets readers master algebra one simple step at a time--at their own speed. "Algebra Demystified" is loaded ...Show synopsisUnlike most books on algebra, this guide lets readers master algebra one simple step at a time--at their own speed. "Algebra Demystified" is loaded with diagrams to reinforce mathematical concepts, along with exercise sets, chapter ending quizzes, and final exams to master the material.Hide synopsis Reviews of Algebra Demystified Some but not many penciled in answers, but I have an eraser(haha). The book was in tact and just what I needed to advance myself and with any textbook, to move to the next level. Very Satisfied!! I give it a Five star rating!:
BCA205 To practice basic arithmetic to enhance reasoning and computational capabilities. Credits: 3 Matrices Symmetric, Skew –symmetric , Hermitian and Skew Hermitian matrices, orthogonal and Unitary matrices, Elementary operation on matrices, Inverse of a matrix , Row rank, Column rank and their equivalence, Rank of a matrix, Eigen Vectors , Eigen values and the Characteristic equation of a matrix , Cayley –Hamilton theorem and its use in findings inverse of a matrices. Vector integration Determinants Determinants and their properties. Differential Equation First order and first degree differential equations, separation of variables, Homogeneous, linear, exact differential equations, second order linear equations with constant coefficients, Orthogonal trajectories.
Ratio and Amp; Proportion Dosage CalculATIO & PROPORTION DOSAGE CALCULATIONS, 2/eoffers an exceptional solution for instructors using the ratio and proportions method of dosage calculations. Streamlined in this edition, it walks readers step-by-step through solving dosage problems using this time-tested technique. Unit I provides a firm foundation with a diagnostic arithmetic test, review of basic math skills, and basic concepts in medication administration. Unit II addresses systems of measurementincluding metric and household medication systems and conversions. Unit III and Unit IV delve into calculating oral and parenteral medications, solutions, infusions, flow rates, pediatric dosages, and daily fluid maintenance. More than just math skills, this is an introduction to the professional context of safe drug administration.
From the Publisher: Discrete Mathematics combines a balance of theory and applications with mathematical rigor and an accessible writing style. The author uses a range of examples to teach core concepts, while corresponding exercises allow students to apply what they learn. Throughout the text, engaging anecdotes and topics of interest inform as well as motivate learners. The text is ideal for one- or two-semester courses and for students who are typically mathematics, mathematics education, or computer science majors. Part I teaches student how to write proofs; Part II focuses on computation and problem solving. The second half of the book may also be suitable for introductory courses in combinatorics and graph theory. Description: Aimed at undergraduate mathematics and computer science students, this book is an excellent introduction to a lot of problems of discrete mathematics. It discusses a number of selected results and methods, mostly from areas of combinatorics and graph theory, ...
Mathematics: An Invitation to Effective Thinking Using careful explanation and intriguing puzzles, the authors invite readers to change their way of thinking to discover and construct mathematical ...Show synopsisUsing careful explanation and intriguing puzzles, the authors invite readers to change their way of thinking to discover and construct mathematical ideas. The authors stress that mathematics involves an analytical way of thinking that can be brought to bear to solve problems in any field of study. 700 illus.Hide synopsis Description:Good. Paperback. May include moderately worn cover, writing,...Good. Paperback. May include moderately worn cover, writing, markings or slight discoloration. SKU: 9781118235706235706
A Guide to MATLABThis book is a short, focused introduction to MATLAB, a comprehen-sive software system for mathematics and technical computing. It willbe useful to both beginning and experienced users. It contains conciseexplanations of essential MATLAB commands, as well as easily under-stood instructions for using MATLAB's programming features, graphi-cal capabilities, and desktop interface. It also includes an introductionto SIMULINK, a companion to MATLAB for system simulation.Written for MATLAB 6, this book can also be used with earlier (andlater) versions of MATLAB. This book contains worked-out examplesof applications of MATLAB to interesting problems in mathematics,engineering, economics, and physics. In addition, it contains explicitinstructions for using MATLAB's Microsoft Word interface to producepolished, integrated, interactive documents for reports, presentations,or online publishing.This book explains everything you need to know to begin usingMATLAB to do all these things and more. Intermediate and advancedusers will find useful information here, especially if they are makingthe switch to MATLAB 6 from an earlier version.Brian R. Hunt is an Associate Professor of Mathematics at the Univer-sity of Maryland. Professor Hunt has coauthored four books on math-ematical software and more than 30 journal articles. He is currentlyinvolved in research on dynamical systems and fractal geometry.Ronald L. Lipsman is a Professor of Mathematics and Associate Deanof the College of Computer, Mathematical, and Physical Sciences at theUniversity of Maryland. Professor Lipsman has coauthored five bookson mathematical software and more than 70 research articles. ProfessorLipsman was the recipient of both the NATO and Fulbright Fellowships.Jonathan M. Rosenberg is a Professor of Mathematics at the Univer-sity of Maryland. Professor Rosenberg is the author of two books onmathematics (one of them coauthored by R. Lipsman and K. Coombes)and the coeditor of Novikov Conjectures, Index Theorems, and Rigidity,a two-volume set from the London Mathematical Society Lecture NoteSeries (Cambridge University Press, 1995). PrefaceMATLAB is an integrated technical computing environment that combinesnumeric computation, advanced graphics and visualization, and a high-level programming language.– statement encapsulates the view of The MathWorks, Inc., the developer ofMATLAB . MATLAB 6 is an ambitious program. It contains hundreds of com-mands to do mathematics. You can use it to graph functions, solve equations,perform statistical tests, and do much more. It is a high-level programminglanguage that can communicate with its cousins, e.g., FORTRAN and C. Youcan produce sound and animate graphics. You can do simulations and mod-eling (especially if you have access not just to basic MATLAB but also to itsaccessory SIMULINK ). You can prepare materials for export to the WorldWide Web. In addition, you can use MATLAB, in conjunction with the wordprocessing and desktop publishing features of Microsoft Word , to combinemathematical computations with text and graphics to produce a polished, in-tegrated, and interactive document.A program this sophisticated contains many features and options. Thereare literally hundreds of useful commands at your disposal. The MATLABhelp documentation contains thousands of entries. The standard references,whether the MathWorks User's Guide for the product, or any of our com-petitors, contain myriad tables describing an endless stream of commands,options, and features that the user might be expected to learn or access.MATLAB is more than a fancy calculator; it is an extremely useful andversatile tool. Even if you only know a little about MATLAB, you can use itto accomplish wonderful things. The hard part, however, is figuring out whichof the hundreds of commands, scores of help pages, and thousands of items ofdocumentation you need to look at to start using it quickly and effectively.That's where we come in.xiii xiv PrefaceWhy We Wrote This BookThe goal of this book is to get you started using MATLAB successfully andquickly. We point out the parts of MATLAB you need to know without over-whelming you with details. We help you avoid the rough spots. We give youexamples of real uses of MATLAB that you can refer to when you're doingyour own work. And we provide a handy reference to the most useful featuresof MATLAB. When you're finished reading this book, you will be able to useMATLAB effectively. You'll also be ready to explore more of MATLAB on yourown.You might not be a MATLAB expert when you finish this book, but youwill be prepared to become one — if that's what you want. We figure you'reprobably more interested in being an expert at your own specialty, whetherthat's finance, physics, psychology, or engineering. You want to use MATLABthe way we do, as a tool. This book is designed to help you become a proficientMATLAB user as quickly as possible, so you can get on with the business athand.Who Should Read This BookThis book will be useful to complete novices, occasional users who want tosharpen their skills, intermediate or experienced users who want to learnabout the new features of MATLAB 6 or who want to learn how to useSIMULINK, and even experts who want to find out whether we know any-thing they don't.You can read through this guide to learn MATLAB on your own. If youremployer (or your professor) has plopped you in front of a computer withMATLAB and told you to learn how to use it, then you'll find the book par-ticularly useful. If you are teaching or taking a course in which you want touse MATLAB as a tool to explore another subject — whether in mathematics,science, engineering, business, or statistics — this book will make a perfectsupplement.As mentioned, we wrote this guide for use with MATLAB 6. If you planto continue using MATLAB 5, however, you can still profit from this book.Virtually all of the material on MATLAB commands in this book applies toboth versions. Only a small amount of material on the MATLAB interface,found mainly in Chapters 1, 3, and 8, is exclusive to MATLAB 6. Preface xvHow This Book Is OrganizedIn writing, we drew on our experience to provide important information asquickly as possible. The book contains a short, focused introduction toMATLAB. It contains practice problems (with complete solutions) so you cantest your knowledge. There are several illuminating sample projects that showyou how MATLAB can be used in real-world applications, and there is an en-tire chapter on troubleshooting.The core of this book consists of about 75 pages: Chapters 1–4 and the begin-ning of Chapter 5. Read that much and you'll have a good grasp of the funda-mentals of MATLAB. Read the rest — the remainder of the Graphics chapteras well as the chapters on M-Books, Programming, SIMULINK and GUIs, Ap-plications, MATLAB and the Internet, Troubleshooting, and the Glossary —and you'll know enough to do a great deal with MATLAB.Here is a detailed summary of the contents of the book.Chapter 1, Getting Started, describes how to start MATLAB on differentplatforms. It tells you how to enter commands, how to access online help, howto recognize the various MATLAB windows you will encounter, and how toexit the application.Chapter 2, MATLAB Basics, shows you how to do elementary mathe-matics using MATLAB. This chapter contains the most essential MATLABcommands.Chapter 3, Interacting with MATLAB, contains an introduction to theMATLAB Desktop interface. This chapter will introduce you to the basicwindow features of the application, to the small program files (M-files) that youwill use to make most effective use of the software, and to a simple method(diary files) of documenting your MATLAB sessions. After completing thischapter, you'll have a better appreciation of the breadth described in the quotethat opens this preface.Practice Set A, Algebra and Arithmetic, contains some simple problems forpracticing your newly acquired MATLAB skills. Solutions are presented atthe end of the book.Chapter 4, Beyond the Basics, contains an explanation of the finer pointsthat are essential for using MATLAB effectively.Chapter 5, MATLAB Graphics, contains a more detailed look at many ofthe MATLAB commands for producing graphics.Practice Set B, Calculus, Graphics, and Linear Algebra, gives you anotherchance to practice what you've just learned. As before, solutions are providedat the end of the book. xvi PrefaceChapter 6, M-Books, contains an introduction to the word processing anddesktop publishing features available when you combine MATLAB withMicrosoft Word.Chapter 7, MATLAB Programming, introduces you to the programmingfeatures of MATLAB. This chapter is designed to be useful both to the noviceprogrammer and to the experienced FORTRAN or C programmer.Chapter 8, SIMULINK and GUIs, consists of two parts. The first part de-scribes the MATLAB companion software SIMULINK, a graphically orientedpackage for modeling, simulating, and analyzing dynamical systems. Manyof the calculations that can be done with MATLAB can be done equally wellwith SIMULINK. If you don't have access to SIMULINK, skip this part ofChapter 8. The second part contains an introduction to the construction anddeployment of graphical user interfaces, that is, GUIs, using MATLAB.Chapter 9, Applications, contains examples, from many different fields, ofsolutions of real-world problems using MATLAB and/or SIMULINK.Practice Set C, Developing Your MATLAB Skills, contains practice problemswhose solutions use the methods and techniques you learned in Chapters 6–9.Chapter 10, MATLAB and the Internet, gives tips on how to post MATLABoutput on the Web.Chapter 11, Troubleshooting, is the place to turn when anything goes wrong.Many common problems can be resolved by reading (and rereading) the advicein this chapter.Next, we have Solutions to the Practice Sets, which contains solutions toall the problems from the three practice sets. The Glossary contains short de-scriptions (with examples) of many MATLAB commands and objects. Thoughnot a complete reference, it is a handy guide to the most important featuresof MATLAB. Finally, there is a complete Index.Conventions Used in This BookWe use distinct fonts to distinguish various entities. When new terms arefirst introduced, they are typeset in an italic font. Output from MATLABis typeset in a monospaced typewriter font; commands that you type forinterpretation by MATLAB are indicated by a boldface version of that font.These commands and responses are often displayed on separate lines as theywould be in a MATLAB session, as in the following example:>> x = sqrt(2*pi + 1)x =2.697 Preface xviiSelectable menu items (from the menu bars in the MATLAB Desktop, figurewindows, etc.) are typeset in a boldface font. Submenu items are separatedfrom menu items by a colon, as in File : Open.... Labels such as the names ofwindows and buttons are quoted, in a "regular" font. File and folder names,as well as Web addresses, are printed in a typewriter font. Finally, namesof keys on your computer keyboard are set in a SMALL CAPS font.We use four special symbols throughout the book. Here they are togetherwith their meanings. Paragraphs like this one contain cross-references to other parts of the book orsuggestions of where you can skip ahead to another chapter.➱ Paragraphs like this one contain important notes. Our favorite is"Save your work frequently." Pay careful attention to theseparagraphs. Paragraphs like this one contain useful tips or point out features of interestin the surrounding landscape. You might not need to think carefully aboutthem on the first reading, but they may draw your attention to some of thefiner points of MATLAB if you go back to them later.Paragraphs like this discuss features of MATLAB's Symbolic MathToolbox, used for symbolic (as opposed to numerical) calculations. If you arenot using the Symbolic Math Toolbox, you can skip these sections.Incidentally, if you are a student and you have purchased the MATLABStudent Version, then the Symbolic Math Toolbox and SIMULINK are auto-matically included with your software, along with basic MATLAB. Caution:The Student Edition of MATLAB, a different product, does not come withSIMULINK.About the AuthorsWe are mathematics professors at the University of Maryland, College Park.We have used MATLAB in our research, in our mathematics courses, for pre-sentations and demonstrations, for production of graphics for books and forthe Web, and even to help our kids do their homework. We hope that you'llfind MATLAB as useful as we do and that this book will help you learn touse it quickly and effectively. Finally, we would like to thank our editor, AlanHarvey, for his personal attention and helpful suggestions. Chapter 1Getting StartedIn this chapter, we will introduce you to the tools you need to begin usingMATLAB effectively. These include: some relevant information on computerplatforms and software versions; installation and location protocols; how tolaunch the program, enter commands, use online help, and recover from hang-ups; a roster of MATLAB's various windows; and finally, how to quit the soft-ware. We know you are anxious to get started using MATLAB, so we will keepthis chapter brief. After you complete it, you can go immediately to Chapter 2to find concrete and simple instructions for the use of MATLAB. We describethe MATLAB interface more elaborately in Chapter 3.Platforms and VersionsIt is likely that you will run MATLAB on a PC (running Windows or Linux)or on some form of UNIX operating system. (The developers of MATLAB,The MathWorks, Inc., are no longer supporting Macintosh. Earlier versions ofMATLAB were available for Macintosh; if you are running one of those, youshould find that our instructions for Windows platforms will suffice for yourneeds.) Unlike previous versions of MATLAB, version 6 looks virtually identi-cal on Windows and UNIX platforms. For definitiveness, we shall assume thereader is using a PC in a Windows environment. In those very few instanceswhere our instructions must be tailored differently for Linux or UNIX users,we shall point it out clearly.➱ We use the word Windows to refer to all flavors of the Windowsoperating system, that is, Windows 95, Windows 98, Windows 2000,Windows Millennium Edition, and Windows NT.1 2 Chapter 1: Getting StartedThis book is written to be compatible with the current version of MATLAB,namely version 6 (also known as Release 12). The vast majority of the MATLABcommands we describe, as well as many features of the MATLAB interface(M-files, diary files, M-books, etc.), are valid for version 5.3 (Release 11), andeven earlier versions in some cases. We also note that the differences betweenthe Professional Version and the Student Version (not the Student Edition)of MATLAB are rather minor and virtually unnoticeable to the new, or evenmid-level, user. Again, in the few instances where we describe a MATLABfeature that is only available in the Professional Version, we highlight thatfact clearly.Installation and LocationIf you intend to run MATLAB on a PC, especially the Student Version, it isquite possible that you will have to install it yourself. You can easily accomplishthis using the product CDs. Follow the installation instructions as you wouldwith any new software you install. At some point in the installation you maybe asked which toolboxes you wish to include in your installation. Unless youhave severe space limitations, we suggest that you install any that seem ofinterest to you or that you think you might use at some point in the future. Weask only that you be sure to include the Symbolic Math Toolbox among thoseyou install. If possible, we also encourage you to install SIMULINK, which isdescribed in Chapter 8.Depending on your version you may also be asked whether you want tospecify certain directory (i.e., folder) locations associated with Microsoft Word.If you do, you will be able to run the M-book interface that is described inChapter 6. If your computer has Microsoft Word, we strongly urge you toinclude these directory locations during installation.If you allow the default settings during installation, then MATLAB willlikely be found in a directory with a name such as matlabR12 or matlab SR12or MATLAB — you may have to hunt around to find it. The subdirectorybinwin32, or perhaps the subdirectory bin, will contain the executable filematlab.exe that runs the program, while the current working directory willprobably be set to matlabR12work.Starting MATLABYou start MATLAB as you would any other software application. On a PC youaccess it via the Start menu, in Programs under a folder such as MatlabR12 Typing in the Command Window 3or Student MATLAB. Alternatively, you may have an icon set up that enablesyou to start MATLAB with a simple double-click. On a UNIX machine, gen-erally you need only type matlab in a terminal window, though you may firsthave to find the matlab/bin directory and add it to your path. Or you mayhave an icon or a special button on your desktop that achieves the task.➱ On UNIX systems, you should not attempt to run MATLAB in thebackground by typing matlab &. This will fail in either the currentor older versions.However you start MATLAB, you will briefly see a window that displaysthe MATLAB logo as well as some MATLAB product information, and then aMATLAB Desktop window will launch. That window will contain a title bar, amenu bar, a tool bar, and five embedded windows, two of which are hidden. Thelargest and most important window is the Command Window on the right. Wewill go into more detail in Chapter 3 on the use and manipulation of the otherfour windows: the Launch Pad, the Workspace browser, the Command Historywindow, and the Current Directory browser. For now we concentrate on theCommand Window to get you started issuing MATLAB commands as quicklyas possible. At the top of the Command Window, you may see some generalinformation about MATLAB, perhaps some special instructions for gettingstarted or accessing help, but most important of all, a line that contains aprompt. The prompt will likely be a double caret (>> or ). If the CommandWindow is "active", its title bar will be dark, and the prompt will be followed bya cursor (a vertical line or box, usually blinking). That is the place where youwill enter your MATLAB commands (see Chapter 2). If the Command Windowis not active, just click in it anywhere. Figure 1-1 contains an example of anewly launched MATLAB Desktop.➱ In older versions of MATLAB, for example 5.3, there is no integratedDesktop. Only the Command Window appears when you launch theapplication. (On UNIX systems, the terminal window from whichyou invoke MATLAB becomes the Command Window.) Commandsthat we instruct you to enter in the Command Window inside theDesktop for version 6 can be entered directly into the CommandWindow in version 5.3 and older versions.Typing in the Command WindowClick in the Command Window to make it active. When a window becomesactive, its titlebar darkens. It is also likely that your cursor will change from 4 Chapter 1: Getting StartedFigure 1-1: A MATLAB Desktop.outline form to solid, or from light to dark, or it may simply appear. Now youcan begin entering commands. Try typing 1+1; then press ENTER or RETURN.Next try factor(123456789), and finally sin(10). Your MATLAB Desktopshould look like Figure 1-2.Online HelpMATLAB has an extensive online help mechanism. In fact, using only thisbook and the online help, you should be able to become quite proficient withMATLAB.You can access the online help in one of several ways. Typing help at thecommand prompt will reveal a long list of topics on which help is available. Justto illustrate, try typing help general. Now you see a long list of "generalpurpose" MATLAB commands. Finally, try help solve to learn about thecommand solve. In every instance above, more information than your screencan hold will scroll by. See the Online Help section in Chapter 2 for instructionsto deal with this.There is a much more user-friendly way to access the online help, namely viathe MATLAB Help Browser. You can activate it in several ways; for example,typing either helpwin or helpdesk at the command prompt brings it up. Interrupting Calculations 5Figure 1-2: Some Simple Commands.Alternatively, it is available through the menu bar under either View or Help.Finally, the question mark button on the tool bar will also invoke the HelpBrowser. We will go into more detail on its features in Chapter 2 — suffice itto say that as in any hypertext browser, you can, by clicking, browse through ahost of command and interface information. Figure 1-3 depicts the MATLABHelp Browser.➱ If you are working with MATLAB version 5.3 or earlier, then typinghelp, help general, or help solve at the command prompt willwork as indicated above. But the entries helpwin or helpdesk callup more primitive, although still quite useful, forms of helpwindows than the robust Help Browser available with version 6.If you are patient, and not overly anxious to get to Chapter 2, you can typedemo to try out MATLAB's demonstration program for beginners.Interrupting CalculationsIf MATLAB is hung up in a calculation, or is just taking too long to performan operation, you can usually abort it by typing CTRL+C (that is, hold down thekey labeled CTRL, or CONTROL, and press C). 6 Chapter 1: Getting StartedFigure 1-3: The MATLAB Help Browser.MATLAB WindowsWe have already described the MATLAB Command Window and the HelpBrowser, and have mentioned in passing the Command History window, Cur-rent Directory browser, Workspace browser, and Launch Pad. These, and seve-ral other windows you will encounter as you work with MATLAB, will allowyou to: control files and folders that you and MATLAB will need to access; writeand edit the small MATLAB programs (that is, M-files) that you will utilize torun MATLAB most effectively; keep track of the variables and functions thatyou define as you use MATLAB; and design graphical models to solve prob-lems and simulate processes. Some of these windows launch separately, andsome are embedded in the Desktop. You can dock some of those that launchseparately inside the Desktop (through the View:Dock menu button), or youcan separate windows inside your MATLAB Desktop out to your computerdesktop by clicking on the curved arrow in the upper right.These features are described more thoroughly in Chapter 3. For now, wewant to call your attention to the other main type of window you will en-counter; namely graphics windows. Many of the commands you issue willgenerate graphics or pictures. These will appear in a separate window. MAT-LAB documentation refers to these as figure windows. In this book, we shall Ending a Session 7also call them graphics windows. In Chapter 5, we will teach you how to gen-erate and manipulate MATLAB graphics windows most effectively. See Figure 2-1 in Chapter 2 for a simple example of a graphics window.➱ Graphics windows cannot be embedded into the MATLAB Desktop.Ending a SessionThe simplest way to conclude a MATLAB session is to type quit at the prompt.You can also click on the special symbol that closes your windows (usually an ×in the upper left- or right-hand corner). Either of these may or may not close allthe other MATLAB windows (which we talked about in the last section) thatare open. You may have to close them separately. Indeed, it is our experiencethat leaving MATLAB-generated windows around after closing the MATLABDesktop may be hazardous to your operating system. Still another way to exitis to use the Exit MATLAB option from the File menu of the Desktop. Beforeyou exit MATLAB, you should be sure to save any variables, print any graphicsor other files you need, and in general clean up after yourself. Some strategiesfor doing so are addressed in Chapter 3. Chapter 2MATLAB BasicsIn this chapter, you will start learning how to use MATLAB to do mathematics.You should read this chapter at your computer, with MATLAB running. Trythe commands in a MATLAB Command Window as you go along. Feel free toexperiment with variants of the examples we present; the best way to find outhow MATLAB responds to a command is to try it. For further practice, you can work the problems in Practice Set A. TheGlossary contains a synopsis of many MATLAB operators, constants,functions, commands, and programming instructions.Input and OutputYou input commands to MATLAB in the MATLAB Command Window. MAT-LAB returns output in two ways: Typically, text or numerical output is re-turned in the same Command Window, but graphical output appears in aseparate graphics window. A sample screen, with both a MATLAB Desktopand a graphics window, labeled Figure No. 1, is shown in Figure 2–1.To generate this screen on your computer, first type 1/2 + 1/3. Then typeezplot('xˆ3 - x'). While MATLAB is working, it may display a "wait" symbol — for example,an hourglass appears on many operating systems. Or it may give no visualevidence until it is finished with its calculation.ArithmeticAs we have just seen, you can use MATLAB to do arithmetic as you would acalculator. You can use "+" to add, "-" to subtract, "*" to multiply, "/" to divide,8 Arithmetic 9Figure 2-1: MATLAB Output.and "ˆ" to exponentiate. For example,>> 3ˆ2 - (5 + 4)/2 + 6*3ans =22.5000MATLAB prints the answer and assigns the value to a variable called ans.If you want to perform further calculations with the answer, you can use thevariable ans rather than retype the answer. For example, you can computethe sum of the square and the square root of the previous answer as follows:>> ansˆ2 + sqrt(ans)ans =510.9934Observe that MATLAB assigns a new value to ans with each calculation.To do more complex calculations, you can assign computed values to variablesof your choosing. For example,>> u = cos(10)u =-0.8391 10 Chapter 2: MATLAB Basics>> v = sin(10)v =-0.5440>> uˆ2 + vˆ2ans =1MATLAB uses double-precision floating point arithmetic, which is accurateto approximately 15 digits; however, MATLAB displays only 5 digits by default.To display more digits, type format long. Then all subsequent numericaloutput will have 15 digits displayed. Type format short to return to 5-digitdisplay.MATLAB differs from a calculator in that it can do exact arithmetic. Forexample, it can add the fractions 1/2 and 1/3 symbolically to obtain the correctfraction 5/6. We discuss how to do this in the section Symbolic Expressions,Variable Precision, and Exact Arithmetic on the next page.AlgebraUsing MATLAB's Symbolic Math Toolbox, you can carry out algebraicor symbolic calculations such as factoring polynomials or solving algebraicequations. Type help symbolic to make sure that the Symbolic Math Tool-box is installed on your system.To perform symbolic computations, you must use syms to declare the vari-ables you plan to use to be symbolic variables. Consider the following seriesof commands:>> syms x y>> (x - y)*(x - y)ˆ2ans =(x-y)^3>> expand(ans) Algebra 11ans =x^3-3*x^2*y+3*x*y^2-y^3>> factor(ans)ans =(x-y)^3 Notice that symbolic output is left-justified, while numeric output isindented. This feature is often useful in distinguishing symbolic outputfrom numerical output.Although MATLAB makes minor simplifications to the expressions youtype, it does not make major changes unless you tell it to. The command ex-pand told MATLAB to multiply out the expression, and factor forced MAT-LAB to restore it to factored form.MATLAB has a command called simplify, which you can sometimes useto express a formula as simply as possible. For example,>> simplify((xˆ3 - yˆ3)/(x - y))ans =x^2+x*y+y^2 MATLAB has a more robust command, called simple, that sometimes doesa better job than simplify. Try both commands on the trigonometricexpression sin(x)*cos(y) + cos(x)*sin(y) to compare — you'll haveto read the online help for simple to completely understand the answer.Symbolic Expressions, Variable Precision, and Exact ArithmeticAs we have noted, MATLAB uses floating point arithmetic for its calculations.Using the Symbolic Math Toolbox, you can also do exact arithmetic with sym-bolic expressions. Consider the following example:>> cos(pi/2)ans =6.1232e-17The answer is written in floating point format and means 6.1232 × 10−17.However, we know that cos(π/2) is really equal to 0. The inaccuracy is dueto the fact that typing pi in MATLAB gives an approximation to π accurate 12 Chapter 2: MATLAB Basicsto about 15 digits, not its exact value. To compute an exact answer, insteadof an approximate answer, we must create an exact symbolic representationof π/2 by typing sym('pi/2'). Now let's take the cosine of the symbolicrepresentation of π/2:>> cos(sym('pi/2'))ans =0This is the expected answer.The quotes around pi/2 in sym('pi/2') create a string consisting of thecharacters pi/2 and prevent MATLAB from evaluating pi/2 as a floatingpoint number. The command sym converts the string to a symbolic expression.The commands sym and syms are closely related. In fact, syms x is equiv-alent to x = sym('x'). The command syms has a lasting effect on its argu-ment (it declares it to be symbolic from now on), while sym has only a tempo-rary effect unless you assign the output to a variable, as in x = sym('x').Here is how to add 1/2 and 1/3 symbolically:>> sym('1/2') + sym('1/3')ans =5/6Finally, you can also do variable-precision arithmetic with vpa. For example,to print 50 digits of√2, type>> vpa('sqrt(2)', 50)ans =1.4142135623730950488016887242096980785696718753769➱ You should be wary of using sym or vpa on an expression thatMATLAB must evaluate before applying variable-precisionarithmetic. To illustrate, enter the expressions 3ˆ45, vpa(3ˆ45),and vpa('3ˆ45'). The first gives a floating point approximation tothe answer, the second — because MATLAB only carries 16-digitprecision in its floating point evaluation of the exponentiation —gives an answer that is correct only in its first 16 digits, and thethird gives the exact answer. See the section Symbolic and Floating Point Numbers in Chapter 4 for detailsabout how MATLAB converts between symbolic and floating point numbers. Managing Variables 13Managing VariablesWe have now encountered three different classes of MATLAB data: floatingpoint numbers, strings, and symbolic expressions. In a long MATLAB sessionit may be hard to remember the names and classes of all the variables youhave defined. You can type whos to see a summary of the names and types ofyour currently defined variables. Here's the output of whos for the MATLABsession displayed in this chapter:>> whosName Size Bytes Classans 1 x 1 226 sym objectu 1 x 1 8 double arrayv 1 x 1 8 double arrayx 1 x 1 126 sym objecty 1 x 1 126 sym objectGrand total is 58 elements using 494 bytesWe see that there are currently five assigned variables in our MATLABsession. Three are of class "sym object"; that is, they are symbolic objects. Thevariables x and y are symbolic because we declared them to be so using syms,and ans is symbolic because it is the output of the last command we executed,which involved a symbolic expression. The other two variables, u and v, areof class "double array". That means that they are arrays of double-precisionnumbers; in this case the arrays are of size 1 × 1 (that is, scalars). The "Bytes"column shows how much computer memory is allocated to each variable.Try assigning u = pi, v = 'pi', and w = sym('pi'), and then typewhos to see how the different data types are described.The command whos shows information about all defined variables, but itdoes not show the values of the variables. To see the value of a variable, simplytype the name of the variable and press ENTER or RETURN.MATLAB commands expect particular classes of data as input, and it isimportant to know what class of data is expected by a given command; the helptext for a command usually indicates the class or classes of input it expects. Thewrong class of input usually produces an error message or unexpected output.For example, type sin('pi') to see how unexpected output can result fromsupplying a string to a function that isn't designed to accept strings.To clear all defined variables, type clear or clear all. You can also type,for example, clear x y to clear only x and y.You should generally clear variables before starting a new calculation.Otherwise values from a previous calculation can creep into the new 14 Chapter 2: MATLAB BasicsFigure 2-2: Desktop with the Workspace Browser.calculation by accident. Finally, we observe that the Workspace browser pre-sents a graphical alternative to whos. You can activate it by clicking on theWorkspace tab, by typing workspace at the command prompt, or throughthe View item on the menu bar. Figure 2-2 depicts a Desktop in which theCommand Window and the Workspace browser contain the same informationas displayed above.Errors in InputIf you make an error in an input line, MATLAB will beep and print an errormessage. For example, here's what happens when you try to evaluate 3uˆ2:>> 3uˆ2??? 3u^2|Error: Missing operator, comma, or semicolon.The error is a missing multiplication operator *. The correct input would be3*uˆ2. Note that MATLAB places a marker (a vertical line segment) at theplace where it thinks the error might be; however, the actual error may haveoccurred earlier or later in the expression. Online Help 15➱ Missing multiplication operators and parentheses are among themost common errors.You can edit an input line by using the UP-ARROW key to redisplay the pre-vious command, editing the command using the LEFT- and RIGHT-ARROW keys,and then pressing RETURN or ENTER. The UP- and DOWN-ARROW keys allow youto scroll back and forth through all the commands you've typed in a MATLABsession, and are very useful when you want to correct, modify, or reenter aprevious command.Online HelpThere are several ways to get online help in MATLAB. To get help on a particu-lar command, enter help followed by the name of the command. For example,help solve will display documentation for solve. Unless you have a largemonitor, the output of help solve will not fit in your MATLAB commandwindow, and the beginning of the documentation will scroll quickly past thetop of the screen. You can force MATLAB to display information one screen-ful at a time by typing more on. You press the space bar to display the nextscreenful, or ENTER to display the next line; type help more for details. Typingmore on affects all subsequent commands, until you type more off.The command lookfor searches the first line of every MATLAB help filefor a specified string (use lookfor -all to search all lines). For example,if you wanted to see a list of all MATLAB commands that contain the word"factor" as part of the command name or brief description, then you wouldtype lookfor factor. If the command you are looking for appears in thelist, then you can use help on that command to learn more about it.The most robust online help in MATLAB 6 is provided through the vastlyimproved Help Browser. The Help Browser can be invoked in several ways: bytyping helpdesk at the command prompt, under the View item in the menubar, or through the question mark button on the tool bar. Upon its launch youwill see a window with two panes: the first, called the Help Navigator, usedto find documentation; and the second, called the display pane, for viewingdocumentation. The display pane works much like a normal web browser. Ithas an address window, buttons for moving forward and backward (among thewindows you have visited), live links for moving around in the documentation,the capability of storing favorite sites, and other such tools.You use the Help Navigator to locate the documentation that you will ex-plore in the display pane. The Help Navigator has four tabs that allow you to 16 Chapter 2: MATLAB Basicsarrange your search for documentation in different ways. The first is the Con-tents tab that displays a tree view of all the documentation topics available.The extent of that tree will be determined by how much you (or your systemadministrator) included in the original MATLAB installation (how many tool-boxes, etc.). The second tab is an Index that displays all the documentationavailable in index format. It responds to your key entry of likely items youwant to investigate in the usual alphabetic reaction mode. The third tab pro-vides the Search mechanism. You type in what you seek, either a functionor some other descriptive term, and the search engine locates correspondingdocumentation that pertains to your entry. Finally, the fourth tab is a rosterof your Favorites. Clicking on an item that appears in any of these tabs bringsup the corresponding documentation in the display pane.The Help Browser has an excellent tutorial describing its own operation.To view it, open the Browser; if the display pane is not displaying the "BeginHere" page, then click on it in the Contents tab; scroll down to the "Usingthe Help Browser" link and click on it. The Help Browser is a powerful andeasy-to-use aid in finding the information you need on various components ofMATLAB. Like any such tool, the more you use it, the more adept you becomeat its use. If you type helpwin to launch the Help Browser, the display pane willcontain the same roster that you see as the result of typing help at thecommand prompt, but the entries will be links.Variables and AssignmentsIn MATLAB, you use the equal sign to assign values to a variable. For instance,>> x = 7x =7will give the variable x the value 7 from now on. Henceforth, whenever MAT-LAB sees the letter x, it will substitute the value 7. For example, if y has beendefined as a symbolic variable, then>> xˆ2 - 2*x*y + yans =49-13*y Solving Equations 17➱ To clear the value of the variable x, type clear x.You can make very general assignments for symbolic variables and thenmanipulate them. For example,>> clear x; syms x y>> z = xˆ2 - 2*x*y + yz =x^2-2*x*y+y>> 5*y*zans =5*y*(x^2-2*x*y+y)A variable name or function name can be any string of letters, digits, andunderscores, provided it begins with a letter (punctuation marks are not al-lowed). MATLAB distinguishes between uppercase and lowercase letters. Youshould choose distinctive names that are easy for you to remember, generallyusing lowercase letters. For example, you might use cubicsol as the nameof the solution of a cubic equation.➱ A common source of puzzling errors is the inadvertent reuse ofpreviously defined variables.MATLAB never forgets your definitions unless instructed to do so. You cancheck on the current value of a variable by simply typing its name.Solving EquationsYou can solve equations involving variables with solve or fzero. For exam-ple, to find the solutions of the quadratic equation x2− 2x − 4 = 0, type>> solve('xˆ2 - 2*x - 4 = 0')ans =[ 5^(1/2)+1][ 1-5^(1/2)]Note that the equation to be solved is specified as a string; that is, it is sur-rounded by single quotes. The answer consists of the exact (symbolic) solutions 18 Chapter 2: MATLAB Basics1 ±√5. To get numerical solutions, type double(ans), or vpa(ans) to dis-play more digits.The command solve can solve higher-degree polynomial equations, as wellas many other types of equations. It can also solve equations involving morethan one variable. If there are fewer equations than variables, you should spec-ify (as strings) which variable(s) to solve for. For example, type solve('2*x -log(y) = 1', 'y') to solve 2x − log y = 1 for y in terms of x. You canspecify more than one equation as well. For example,>> [x, y] = solve('xˆ2 - y = 2', 'y - 2*x = 5')x =[ 1+2*2^(1/2)][ 1-2*2^(1/2)]y =[ 7+4*2^(1/2)][ 7-4*2^(1/2)]This system of equations has two solutions. MATLAB reports the solution bygiving the two x values and the two y values for those solutions. Thus the firstsolution consists of the first value of x together with the first value of y. Youcan extract these values by typing x(1) and y(1):>> x(1)ans =1+2*2^(1/2)>> y(1)ans =7+4*2^(1/2)The second solution can be extracted with x(2) and y(2).Note that in the preceding solve command, we assigned the output to thevector [x, y]. If you use solve on a system of equations without assigningthe output to a vector, then MATLAB does not automatically display the valuesof the solution:>> sol = solve('xˆ2 - y = 2', 'y - 2*x = 5') Solving Equations 19sol =x: [2x1 sym]y: [2x1 sym]To see the vectors of x and y values of the solution, type sol.x and sol.y. Tosee the individual values, type sol.x(1), sol.y(1), etc.Some equations cannot be solved symbolically, and in these cases solvetries to find a numerical answer. For example,>> solve('sin(x) = 2 - x')ans =1.1060601577062719106167372970301Sometimes there is more than one solution, and you may not get what youexpected. For example,>> solve('exp(-x) = sin(x)')ans =-2.0127756629315111633360706990971+2.7030745115909622139316148044265*iThe answer is a complex number; the i at the end of the answer stands forthe number√−1. Though it is a valid solution of the equation, there are alsoreal number solutions. In fact, the graphs of exp(−x) and sin(x) are shown inFigure 2-3; each intersection of the two curves represents a solution of theequation e−x= sin(x).You can numerically find the solutions shown on the graph with fzero,which looks for a zero of a given function near a specified value of x. A solutionof the equation e−x= sin(x) is a zero of the function e−x− sin(x), so to find thesolution near x = 0.5 type>> fzero(inline('exp(-x) - sin(x)'), 0.5)ans =0.5885Replace 0.5 with 3 to find the next solution, and so forth. In the example above, the command inline, which we will discuss further inthe section User-Defined Functions below, converts its string argument to a 20 Chapter 2: MATLAB Basics0 1 2 3 4 5 6 7 8 9 10-1-0.500.51xexp(-x) and sin(x)Figure 2-3function data class. This is the type of input fzero expects as its firstargument. In current versions of MATLAB, fzero also accepts a string expression withindependent variable x, so that we could have run the command abovewithout using inline, but this feature is no longer documented in the helptext for fzero and may be removed in future versions.Vectors and MatricesMATLAB was written originally to allow mathematicians, scientists, andengineers to handle the mechanics of linear algebra — that is, vectors andmatrices — as effortlessly as possible. In this section we introduce theseconcepts. Vectors and Matrices 21VectorsA vector is an ordered list of numbers. You can enter a vector of any length inMATLAB by typing a list of numbers, separated by commas or spaces, insidesquare brackets. For example,>> Z = [2,4,6,8]Z =2 4 6 8>> Y = [4 -3 5 -2 8 1]Y =4 -3 5 -2 8 1Suppose you want to create a vector of values running from 1 to 9. Here'show to do it without typing each number:>> X = 1:9X =1 2 3 4 5 6 7 8 9The notation 1:9 is used to represent a vector of numbers running from 1 to9 in increments of 1. The increment can be specified as the second of threearguments:>> X = 0:2:10X =0 2 4 6 8 10You can also use fractional or negative increments, for example, 0:0.1:1 or100:-1:0.The elements of the vector X can be extracted as X(1), X(2), etc. For ex-ample,>> X(3)ans =4 22 Chapter 2: MATLAB BasicsTo change the vector X from a row vector to a column vector, put a prime (')after X:>> X'ans =0246810You can perform mathematical operations on vectors. For example, to squarethe elements of the vector X, type>> X.ˆ2ans =0 4 16 36 64 100The period in this expression is very important; it says that the numbersin X should be squared individually, or element-by-element. Typing Xˆ2 wouldtell MATLAB to use matrix multiplication to multiply X by itself and wouldproduce an error message in this case. (We discuss matrices below and inChapter 4.) Similarly, you must type .* or ./ if you want to multiply or di-vide vectors element-by-element. For example, to multiply the elements of thevector X by the corresponding elements of the vector Y, type>> X.*Yans =0 -6 20 -12 64 10Most MATLAB operations are, by default, performed element-by-element.For example, you do not type a period for addition and subtraction, and youcan type exp(X) to get the exponential of each number in X (the matrix ex-ponential function is expm). One of the strengths of MATLAB is its ability toefficiently perform operations on vectors. Vectors and Matrices 23MatricesA matrix is a rectangular array of numbers. Row and column vectors, whichwe discussed above, are examples of matrices. Consider the 3 × 4 matrixA =1 2 3 45 6 7 89 10 11 12 .It can be entered in MATLAB with the command>> A = [1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12]A =1 2 3 45 6 7 89 10 11 12Note that the matrix elements in any row are separated by commas, and therows are separated by semicolons. The elements in a row can also be separatedby spaces.If two matrices A and B are the same size, their (element-by-element) sumis obtained by typing A + B. You can also add a scalar (a single number) to amatrix; A + c adds c to each element in A. Likewise, A - B represents thedifference of A and B, and A - c subtracts the number c from each elementof A. If A and B are multiplicatively compatible (that is, if A is n × m and B ism× ), then their product A*B is n × . Recall that the element of A*B in theith row and jth column is the sum of the products of the elements from theith row of A times the elements from the jth column of B, that is,(A ∗ B)ij =mk=1AikBkj, 1 ≤ i ≤ n, 1 ≤ j ≤ .The product of a number c and the matrix A is given by c*A, and A' representsthe conjugate transpose of A. (For more information, see the online help forctranspose and transpose.)A simple illustration is given by the matrix product of the 3 × 4 matrix Aabove by the 4 × 1 column vector Z':>> A*Z'ans =60140220 24 Chapter 2: MATLAB BasicsThe result is a 3 × 1 matrix, in other words, a column vector. MATLAB has many commands for manipulating matrices. You can readabout them in the section More about Matrices in Chapter 4 and in the onlinehelp; some of them are illustrated in the section Linear Economic Models inChapter 9.Suppressing OutputTyping a semicolon at the end of an input line suppresses printing of theoutput of the MATLAB command. The semicolon should generally be usedwhen defining large vectors or matrices (such as X = -1:0.1:2;). It canalso be used in any other situation where the MATLAB output need not bedisplayed.FunctionsIn MATLAB you will use both built-in functions as well as functions that youcreate yourself.Built-in FunctionsMATLAB has many built-in functions. These include sqrt, cos, sin, tan,log, exp, and atan (for arctan) as well as more specialized mathematicalfunctions such as gamma, erf, and besselj. MATLAB also has several built-in constants, including pi (the number π), i (the complex number i =√−1),and Inf (∞). Here are some examples:>> log(exp(3))ans =3The function log is the natural logarithm, called "ln" in many texts. Nowconsider>> sin(2*pi/3)ans =0.8660 Functions 25To get an exact answer, you need to use a symbolic argument:>> sin(sym('2*pi/3'))ans =1/2*3^(1/2)User-Defined FunctionsIn this section we will show how to use inline to define your own functions.Here's how to define the polynomial function f (x) = x2+ x + 1:>> f = inline('xˆ2 + x + 1', 'x')f =Inline function:f(x) = x^2 + x + 1The first argument to inline is a string containing the expression definingthe function. The second argument is a string specifying the independentvariable. The second argument to inline can be omitted, in which case MATLAB will"guess" what it should be, using the rules about "Default Variables" to bediscussed later at the end of Chapter 4.Once the function is defined, you can evaluate it:>> f(4)ans =21MATLAB functions can operate on vectors as well as scalars. To make aninline function that can act on vectors, we use MATLAB's vectorize function.Here is the vectorized version of f (x) = x2+ x + 1:>> f1 = inline(vectorize('xˆ2 + x + 1'), 'x')f1 =Inline function:f1(x) = x.^2 + x + 1 26 Chapter 2: MATLAB BasicsNote that ^ has been replaced by .^. Now you can evaluate f1 on a vector:>> f1(1:5)ans =3 7 13 21 31You can plot f1, using MATLAB graphics, in several ways that we will explorein the next section. We conclude this section by remarking that one can alsodefine functions of two or more variables:>> g = inline('uˆ2 + vˆ2', 'u', 'v')g =Inline function:g(u,v) = u^2+v^2GraphicsIn this section, we introduce MATLAB's two basic plotting commands andshow how to use them.Graphing with ezplotThe simplest way to graph a function of one variable is with ezplot, whichexpects a string or a symbolic expression representing the function to be plot-ted. For example, to graph x2+ x + 1 on the interval −2 to 2 (using the stringform of ezplot), type>> ezplot('xˆ2 + x + 1', [-2 2])The plot will appear on the screen in a new window labeled "Figure No. 1".We mentioned that ezplot accepts either a string argument or a symbolicexpression. Using a symbolic expression, you can produce the plot in Figure 2-4with the following input:>> syms x>> ezplot(xˆ2 + x + 1, [-2 2]) Graphs can be misleading if you do not pay attention to the axes. Forexample, the input ezplot(xˆ2 + x + 3, [-2 2]) produces a graph Graphics 27-2 -1.5 -1 -0.5 0 0.5 1 1.5 21234567xx2+ x + 1Figure 2-4that looks identical to the previous one, except that the vertical axis hasdifferent tick marks (and MATLAB assigns the graph a different title).Modifying GraphsYou can modify a graph in a number of ways. You can change the title abovethe graph in Figure 2-4 by typing (in the Command Window, not the figurewindow)>> title 'A Parabola'You can add a label on the horizontal axis with xlabel or change the labelon the vertical axis with ylabel. Also, you can change the horizontal andvertical ranges of the graph with axis. For example, to confine the verticalrange to the interval from 1 to 4, type>> axis([-2 2 1 4])The first two numbers are the range of the horizontal axis; both ranges must 28 Chapter 2: MATLAB Basicsbe included, even if only one is changed. We'll examine more options for ma-nipulating graphs in Chapter 5.To close the graphics window select File : Close from its menu bar, typeclose in the Command Window, or kill the window the way you would closeany other window on your computer screen.Graphing with plotThe command plot works on vectors of numerical data. The basic syntax isplot(X, Y) where X and Y are vectors of the same length. For example,>> X = [1 2 3];>> Y = [4 6 5];>> plot(X, Y)The command plot(X, Y) considers the vectors X and Y to be lists of the xand y coordinates of successive points on a graph and joins the points withline segments. So, in Figure 2-5, MATLAB connects (1, 4) to (2, 6) to (3, 5).1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 344.24.44.64.855.25.45.65.86Figure 2-5 Graphics 29To plot x2+ x + 1 on the interval from −2 to 2 we first make a list X ofx values, and then type plot(X, X.ˆ2 + X + 1). We need to use enoughx values to ensure that the resulting graph drawn by "connecting the dots"looks smooth. We'll use an increment of 0.1. Thus a recipe for graphing theparabola is>> X = -2:0.1:2;>> plot(X, X.ˆ2 + X + 1)The result appears in Figure 2-6. Note that we used a semicolon to suppressprinting of the 41-element vector X. Note also that the command>> plot(X, f1(X))would produce the same results (f1 is defined earlier in the section User-Defined Functions).-2 -1.5 -1 -0.5 0 0.5 1 1.5 201234567Figure 2-6 30 Chapter 2: MATLAB Basics We describe more of MATLAB's graphics commands in Chapter 5.For now, we content ourselves with demonstrating how to plot a pair ofexpressions on the same graph.Plotting Multiple CurvesEach time you execute a plotting command, MATLAB erases the old plot anddraws a new one. If you want to overlay two or more plots, type hold on.This command instructs MATLAB to retain the old graphics and draw anynew graphics on top of the old. It remains in effect until you type hold off.Here's an example using ezplot:>> ezplot('exp(-x)', [0 10])>> hold on>> ezplot('sin(x)', [0 10])>> hold off>> title 'exp(-x) and sin(x)'The result is shown in Figure 2-3 earlier in this chapter. The commands holdon and hold off work with all graphics commands.With plot, you can plot multiple curves directly. For example,>> X = 0:0.1:10;>> plot(X, exp(-X), X, sin(X))Note that the vector of x coordinates must be specified once for each functionbeing plotted. Chapter 3Interacting withMATLABIn this chapter we describe an effective procedure for working with MATLAB,and for preparing and presenting the results of a MATLAB session. In parti-cular we will discuss some features of the MATLAB interface and the use ofscript M-files, function M-files, and diary files. We also give some simple hintsfor debugging your M-files.The MATLAB InterfaceMATLAB 6 has a new interface called the MATLAB Desktop. Embedded insideit is the Command Window that we described in Chapter 2. If you are usingMATLAB 5, then you will only see the Command Window. In that case youshould skip the next subsection and proceed directly to the Menu and ToolBars subsection below.The DesktopBy default, the MATLAB Desktop (Figure 1-1 in Chapter 1) contains fivewindows inside it, the Command Window on the right, the Launch Pad andthe Workspace browser in the upper left, and the Command History windowand Current Directory browser in the lower left. Note that there are tabs foralternating between the Launch Pad and the Workspace browser, or betweenthe Command History window and Current Directory browser. Which of thefive windows are currently visible can be adjusted with the View : DesktopLayout menu at the top of the Desktop. (For example, with the Simple option,you see only the Command History and Command Window, side-by-side.) Thesizes of the windows can be adjusted by dragging their edges with the mouse.31 32 Chapter 3: Interacting with MATLABThe Command Window is where you type the commands and instructionsthat cause MATLAB to evaluate, compute, draw, and perform all the otherwonderful magic that we describe in this book. The Command History windowcontains a running history of the commands that you type into the CommandWindow. It is useful in two ways. First, it lets you see at a quick glance arecord of the commands that you have entered previously. Second, it can saveyou some typing time. If you click on an entry in the Command History with theright mouse button, it becomes highlighted and a menu of options appears.You can, for example, select Copy, then click with the right mouse buttonin the Command Window and select Paste, whereupon the command youselected will appear at the command prompt and be ready for execution orediting. There are many other options that you can learn by experimenting;for instance, if you double-click on an entry in the Command History then itwill be executed immediately in the Command Window.The Launch Pad window is basically a series of shortcuts that enable you toaccess various features of the MATLAB software with a double-click. You canuse it to start SIMULINK, run demos of various toolboxes, use MATLAB webtools, open the Help Browser, and more. We recommend that you experimentwith the entries in the Launch Pad to gain familiarity with its features.The Workspace browser and Current Directory browser will be describedin separate subsections below.Each of the five windows in the Desktop contains two small buttons in theupper right corner. The × allows you to close the window, while the curvedarrow will "undock" the window from the Desktop (you can return it to theDesktop by selecting Dock from the View menu of the undocked window).You can also customize which windows appear inside the Desktop using itsView menu. While the Desktop provides some new features and a common interface forboth the Windows and UNIX versions of MATLAB 6, it may also run moreslowly than the MATLAB 5 Command Window interface, especially on oldercomputers. You can run MATLAB 6 with the old interface by starting theprogram with the command matlab /nodesktop on a Windows system ormatlab -nodesktop on a UNIX system. If you are a Windows user, youprobably start MATLAB by double-clicking on an icon. If so, you can createan icon to start MATLAB without the Desktop feature as follows. First, clickthe right mouse button on the MATLAB icon and select Create Shortcut. Anew, nearly identical icon will appear on your screen (possibly behind awindow — you may need to hunt for it). Next, click the right mouse buttonon the new icon, and select Properties. In the panel that pops up, select the The MATLAB Interface 33Shortcut tab, and in the "Target" box, add to the end of the executable filename a space followed by /nodesktop. (Notice that you can also change thedefault working directory in the "Start in" box.) Click OK, and your new iconis all set; you may want to rename it by clicking on it again with the rightmouse button, selecting Rename, and typing the new name.Menu and Tool BarsThe MATLAB Desktop includes a menu bar and a tool bar; the tool bar containsbuttons that give quick access to some of the items you can select through themenu bar. On a Windows system, the MATLAB 5 Command Window has amenu bar and tool bar that are similar, but not identical, to those of MATLAB6. For example, its menus are arranged differently and its tool bar has buttonsthat open the Workspace browser and Path Browser, described below. Whenreferring to menu and tool bar items below, we will describe the MATLAB 6Desktop interface.➱ Many of the menu selections and tool bar buttons cause a newwindow to appear on your screen. If you are using a UNIX system,keep in mind the following caveats as you read the rest of thischapter. First, some of the pop-up windows that we describe areavailable on some UNIX systems but unavailable on others,depending (for instance) on the operating system. Second, we willoften describe how to use both the command line and the menu andtool bars to perform certain tasks, though only the command line isavailable on some UNIX systems.The WorkspaceIn Chapter 2, we introduced the commands clear and whos, which can beused to keep track of the variables you have defined in your MATLAB session.The complete collection of defined variables is referred to as the Workspace,which you can view using the Workspace browser. You can make the browserappear by typing workspace or, in the default layout of the MATLAB Desktop,by clicking on the Workspace tab in the Launch Pad window (in a MATLAB5 Command Window select File:Show Workspace instead). The Workspacebrowser contains a list of the current variables and their sizes (but not theirvalues). If you double-click on a variable, its contents will appear in a newwindow called the Array Editor, which you can use to edit individual entriesin a vector or matrix. (The command openvar also will open the Array Editor.) 34 Chapter 3: Interacting with MATLABYou can remove a variable from the Workspace by selecting it in the Workspacebrowser and choosing Edit:Delete.If you need to interrupt a session and don't want to be forced to recomputeeverything later, then you can save the current Workspace with save. Forexample, typing save myfile saves the values of all currently defined vari-ables in a file called myfile.mat. To save only the values of the variables Xand Y, type>> save myfile X YWhen you start a new session and want to recover the values of those variables,use load. For example, typing load myfile restores the values of all thevariables stored in the file myfile.mat.The Working DirectoryNew files you create from within MATLAB will be stored in your currentworking directory. You may want to change this directory from its defaultlocation, or you may want to maintain different working directories for dif-ferent projects. To create a new working directory you must use the standardprocedure for creating a directory in your operating system. Then you canmake this directory your current working directory in MATLAB by using cd,or by selecting this directory in the "Current Directory" box on the Desktoptool bar.For example, on a Windows computer, you could create a directory calledC:ProjectA. Then in MATLAB you would type>> cd C:ProjectAto make it your current working directory. You will then be able to read andwrite files in this directory in your current MATLAB session.If you only need to be able to read files from a certain directory, an alterna-tive to making it your working directory is to add it to the path of directoriesthat MATLAB searches to find files. The current working directory and thedirectories in your path are the only places MATLAB searches for files, unlessyou explicitly type the directory name as part of the file name. To add thedirectory C:ProjectA to your path, type>> addpath C:ProjectAWhen you add a directory to the path, the files it contains remain available forthe rest of your session regardless of whether you subsequently add another The MATLAB Interface 35directory to the path or change the working directory. The potential disadvan-tage of this approach is that you must be careful when naming files. WhenMATLAB searches for files, it uses the first file with the correct name that itfinds in the path list, starting with the current working directory. If you usethe same name for different files in different directories in your path, you canrun into problems.You can also control the MATLAB search path from the Path Browser.To open the Path Browser, type editpath or pathtool, or select File:SetPath.... The Path Browser consists of a panel, with a list of directories in thecurrent path, and several buttons. To add a directory to the path list, clickon Add Folder... or Add with Subfolders..., depending on whether or notyou want subdirectories to be included as well. To remove a directory, click onRemove. The buttons Move Up and Move Down can be used to reorder thedirectories in the path. Note that you can use the Current Directory browser toexamine the files in the working directory, and even to create subdirectories,move M-files around, etc. The information displayed in the main areas of the Path Browser can also beobtained from the command line. To see the current working directory, typepwd. To list the files in the working directory type either ls or dir. To seethe current path list that MATLAB will search for files, type path. If you have many toolboxes installed, path searches can be slow, especiallywith lookfor. Removing the toolboxes you are not currently using from theMATLAB path is one way to speed up execution.Using the Command WindowWe have already described in Chapters 1 and 2 how to enter commands in theMATLAB Command Window. We continue that description here, presentingan example that will serve as an introduction to our discussion of M-files.Suppose you want to calculate the values ofsin(0.1)/0.1, sin(0.01)/0.01, and sin(0.001)/0.001to 15 digits. Such a simple problem can be worked directly in the CommandWindow. Here is a typical first try at a solution, together with the responsethat MATLAB displays in the Command Window:>> x = [0.1, 0.01, 0.001];>> y = sin(x)./x 36 Chapter 3: Interacting with MATLABy =0.9983 1.0000 1.0000After completing a calculation, you will often realize that the result is notwhat you intended. The commands above displayed only 5 digits, not 15. Todisplay 15 digits, you need to type the command format long and thenrepeat the line that defines y. In this case you could simply retype the latterline, but in general retyping is time consuming and error prone, especially forcomplicated problems. How can you modify a sequence of commands withoutretyping them?For simple problems, you can take advantage of the command history fea-ture of MATLAB. Use the UP- and DOWN-ARROW keys to scroll through the listof commands that you have used recently. When you locate the correct com-mand line, you can use the LEFT- and RIGHT-ARROW keys to move around in thecommand line, deleting and inserting changes as necessary, and then pressthe ENTER key to tell MATLAB to evaluate the modified command. You canalso copy and paste previous command lines from the Command Window, orin the MATLAB 6 Desktop from the Command History window as describedearlier in this chapter. For more complicated problems, however, it is better touse M-files.M-FilesFor complicated problems, the simple editing tools provided by the CommandWindow and its history mechanism are insufficient. A much better approachis to create an M-file. There are two different kinds of M-files: script M-filesand function M-files. We shall illustrate the use of both types of M-files as wepresent different solutions to the problem described above.M-files are ordinary text files containing MATLAB commands. You can cre-ate and modify them using any text editor or word processor that is capable ofsaving files as plain ASCII text. (Such text editors include notepad in Win-dows or emacs, textedit, and vi in UNIX.) More conveniently, you can usethe built-in Editor/Debugger, which you can start by typing edit, either byitself (to edit a new file) or followed by the name of an existing M-file in thecurrent working directory. You can also use the File menu or the two leftmostbuttons on the tool bar to start the Editor/Debugger, either to create a newfile or to open an existing file. Double-clicking on an M-file in the CurrentDirectory browser will also open it in the Editor/Debugger. M-Files 37Script M-FilesWe now show how to construct a script M-file to solve the mathematical prob-lem described earlier. Create a file containing the following lines:format longx = [0.1, 0.01, 0.001];y = sin(x)./xWe will assume that you have saved this file with the name task1.m in yourworking directory, or in some directory on your path. You can name the fileany way you like (subject to the usual naming restrictions on your operatingsystem), but the ".m" suffix is mandatory.You can tell MATLAB to run (or execute) this script by typing task1 inthe Command Window. (You must not type the ".m" extension here; MATLABautomatically adds it when searching for M-files.) The output — but not thecommands that produce them — will be displayed in the Command Window.Now the sequence of commands can easily be changed by modifying the M-filetask1.m. For example, if you also wish to calculate sin(0.0001)/0.0001, youcan modify the M-file to readformat longx = [0.1, 0.01, 0.001, 0.0001];y = sin(x)./xand then run the modified script by typing task1. Be sure to save yourchanges to task1.m first; otherwise, MATLAB will not recognize them. Anyvariables that are set by the running of a script M-file will persist exactlyas if you had typed them into the Command Window directly. For example,the program above will cause all future numerical output to be displayedwith 15 digits. To revert to 5-digit format, you would have to type formatshort.Echoing Commands. As mentioned above, the commands in a script M-filewill not automatically be displayed in the Command Window. If you want thecommands to be displayed along with the results, use echo:echo onformat longx = [0.1, 0.01, 0.001];y = sin(x)./xecho off 38 Chapter 3: Interacting with MATLABAdding Comments. It is worthwhile to include comments in a lengthly scriptM-file. These comments might explain what is being done in the calculation,or they might interpret the results of the calculation. Any line in a script M-filethat begins with a percent sign is treated as a comment and is not executed byMATLAB. Here is our new version of task1.m with a few comments added:echo on% Turn on 15 digit displayformat longx = [0.1, 0.01, 0.001];y = sin(x)./x% These values illustrate the fact that the limit of% sin(x)/x as x approaches 0 is 1.echo offWhen adding comments to a script M-file, remember to put a percent sign atthe beginning of each line. This is particularly important if your editor startsa new line automatically while you are typing a comment. If you use echoon in a script M-file, then MATLAB will also echo the comments, so they willappear in the Command Window.Structuring Script M-Files. For the results of a script M-file to be reproducible,the script should be self-contained, unaffected by other variables that youmight have defined elsewhere in the MATLAB session, and uncorrupted byleftover graphics. With this in mind, you can type the line clear all at thebeginning of the script, to ensure that previous definitions of variables donot affect the results. You can also include the close all command at thebeginning of a script M-file that creates graphics, to close all graphics windowsand start with a clean slate.Here is our example of a complete, careful, commented solution to theproblem described above:% Remove old variable definitionsclear all% Remove old graphics windowsclose all% Display the command lines in the command windowecho on% Turn on 15 digit displayformat long M-Files 39% Define the vector of values of the independent variablex = [0.1, 0.01, 0.001];% Compute the desired valuesy = sin(x)./x% These values illustrate the fact that the limit of% sin(x)/x as x approaches 0 is equal to 1.echo off Sometimes you may need to type, either in the Command Window or in anM-file, a command that is too long to fit on one line. If so, when you get nearthe end of a line you can type ... (that is, three successive periods) followedby ENTER, and continue the command on the next line. In the CommandWindow, you will not see a command prompt on the new line.Function M-FilesYou often need to repeat a process several times for different input values of aparameter. For example, you can provide different inputs to a built-in functionto find an output that meets a given criterion. As you have already seen, youcan use inline to define your own functions. In many situations, however,it is more convenient to define a function using an M-file instead of an inlinefunction.Let us return to the problem described above, where we computed somevalues of sin(x)/x with x = 10−bfor several values of b. Suppose, in addition,that you want to find the smallest value of b for which sin(10−b)/(10−b) and 1agree to 15 digits. Here is a function M-file called sinelimit.m designed tosolve that problem:function y = sinelimit(c)% SINELIMIT computes sin(x)/x for x = 10ˆ(-b),% where b = 1, ..., c.format longb = 1:c;x = 10.ˆ(-b);y = (sin(x)./x)';Like a script M-file, a function M-file is a plain text file that should reside inyour MATLAB working directory. The first line of the file contains a function 40 Chapter 3: Interacting with MATLABstatement, which identifies the file as a function M-file. The first line specifiesthe name of the function and describes both its input arguments (or parame-ters) and its output values. In this example, the function is called sinelimit.The file name and the function name should match.The function sinelimit takes one input argument and returns one out-put value, called c and y (respectively) inside the M-file. When the functionfinishes executing, its output will be assigned to ans (by default) or to any othervariable you choose, just as with a built-in function. The remaining lines ofthe M-file define the function. In this example, b is a row vector consistingof the integers from 1 to c. The vector y contains the results of computingsin(x)/x where x = 10−b; the prime makes y a column vector. Notice that theoutput of the lines defining b, x, and y is suppressed with a semicolon. Ingeneral, the output of intermediate calculations in a function M-file should besuppressed. Of course, when we run the M-file above, we do want to see the results ofthe last line of the file, so a natural impulse would be to avoid putting asemicolon on this last line. But because this is a function M-file, running itwill automatically display the contents of the designated output variable y.Thus if we did not put a semicolon at the end of the last line, we would seethe same numbers twice when we run the function! Note that the variables used in a function M-file, such as b, x, and y insinelimit.m, are local variables. This means that, unlike the variables thatare defined in a script M-file, these variables are completely unrelated to anyvariables with the same names that you may have used in the CommandWindow, and MATLAB does not remember their values after the functionM-file is executed. For further information, see the section Variables inFunction M-files in Chapter 4.Here is an example that shows how to use the function sinelimit:>> sinelimit(5)ans =0.998334166468280.999983333416670.999999833333340.999999998333330.99999999998333None of the values of b from 1 to 5 yields the desired answer, 1, to 15 digits. Presenting Your Results 41Judging from the output, you can expect to find the answer to the question weposed above by typing sinelimit(10). Try it!LoopsA loop specifies that a command or group of commands should be repeatedseveral times. The easiest way to create a loop is to use a for statement. Hereis a simple example that computes and displays 10! = 10 · 9 · 8 · · · 2 · 1:f = 1;for n = 2:10f = f*n;endfThe loop begins with the for statement and ends with the end statement. Thecommand between those statements is executed a total of nine times, once foreach value of n from 2 to 10. We used a semicolon to suppress intermediateoutput within the loop. To see the final output, we then needed to type f afterthe end of the loop. Without the semicolon, MATLAB would display each ofthe intermediate values 2!, 3!, . . . .We have presented the loop above as you might type it into an M-file; inden-tation is not required by MATLAB, but it helps human readers distinguish thecommands within the loop. If you type the commands above directly to theMATLAB prompt, you will not see a new prompt after entering the for state-ment. You should continue typing, and after you enter the end statement,MATLAB will evaluate the entire loop and display a new prompt. If you use a loop in a script M-file with echo on in effect, the commands willbe echoed every time through the loop. You can avoid this by inserting thecommand echo off just before the end statement and inserting echo onjust afterward; then each command in the loop (except end) will be echoedonce.Presenting Your ResultsSometimes you may want to show other people the results of a script M-filethat you have created. For a polished presentation, you should use an M-book,as described in Chapter 6, or import your results into another program, such 42 Chapter 3: Interacting with MATLABas a word processor, or convert your results to HTML format, by the proceduresdescribed in Chapter 10. But to share your results more informally, you cangive someone else your M-file, assuming that person has a copy of MATLABon which to run it, or you can provide the output you obtained. Either way,you should remember that the reader is not nearly as familiar with the M-fileas you are; it is your responsibility to provide guidance. You can greatly enhance the readability of your M-file by including frequentcomments. Your comments should explain what is being calculated, so thatthe reader can understand your procedures and strategies. Once you've donethe calculations, you can also add comments that interpret the results.If your audience is going to run your M-files, then you should make liberaluse of the command pause. Each time MATLAB reaches a pause statement,it stops executing the M-file until the user presses a key. Pauses should beplaced after important comments, after each graph, and after critical pointswhere your script generates numerical output. These pauses allow the viewerto read and understand your results.Diary FilesHere is an effective way to save the output of your M-file in a way that others(and you!) can later understand. At the beginning of a script M-file, such astask1.m, you can include the commandsdelete task1.txtdiary task1.txtecho onThe script M-file should then end with the commandsecho offdiary offThe first diary command causes all subsequent input to and output fromthe Command Window to be copied into the specified file — in this case,task1.txt. The diary file task1.txt is a plain text file that is suitable forprinting or importing into another program.By using delete at the beginning of the M-file, you ensure that the file onlycontains the output of the current script. If you omit the delete command,then the diary command will add any new output to the end of an existing file,and the file task1.txt can end up containing the results of several runs ofthe M-file. (Putting the delete command in the script will lead to a harmless Presenting Your Results 43warning message about a nonexistent file the first time you run the script.)You can also get extraneous output in a diary file if you type CTRL+C to halt ascript containing a diary command. If this happens, you should type diaryoff in the Command Window before running the script again.Presenting GraphicsAs indicated in Chapters 1 and 2, graphics appear in a separate window. Youcan print the current figure by selecting File : Print... in the graphics window.Alternatively, the command print (without any arguments) causes the figurein the current graphics window to be printed on your default printer. Sinceyou probably don't want to print the graphics every time you run a script, youshould not include a bare print statement in an M-file. Instead, you shoulduse a form of print that sends the output to a file. It is also helpful to givereasonable titles to your figures and to insert pause statements into yourscript so that viewers have a chance to see the figure before the rest of thescript executes. For example,xx = 2*pi*(0:0.02:1);plot(xx, sin(xx))% Put a title on the figure.title('Figure A: Sine Curve')pause% Store the graph in the file figureA.eps.print -deps figureAThe form of print used in this script does not send anything to the printer.Instead, it causes the current figure to be written to a file in the currentworking directory called figureA.eps in Encapsulated PostScript format.This file can be printed later on a PostScript printer, or it can be imported intoanother program that recognizes the EPS format. Type help print to seehow to save your graph in a variety of other formats that may be suitable foryour particular printer or application.As a final example involving graphics, let's consider the problem of plottingthe functions sin(x), sin(2x), and sin(3x) on the same set of axes. This is atypical example; we often want to plot several similar curves whose equationsdepend on a parameter. Here is a script M-file solution to the problem:echo on% Define the x values.x = 2*pi*(0:0.01:1); 44 Chapter 3: Interacting with MATLAB% Remove old graphics, and get ready for several new ones.close all; axes; hold on% Run a loop to plot three sine curves.for c = 1:3plot(x, sin(c*x))echo offendecho onhold off% Put a title on the figure.title('Several Sine Curves')pauseThe result is shown in Figure 3-1.0 1 2 3 4 5 6 7-1-0.8-0.6-0.4-0.200.20.40.60.81Several Sine CurvesFigure 3-1 Presenting Your Results 45Let's analyze this solution. We start by defining the values to use on the xaxis. The command close all removes all existing graphics windows; axesstarts a fresh, empty graphics window; and hold on lets MATLAB know thatwe want to draw several curves on the same set of axes. The lines betweenfor and end constitute a for loop, as described above. The important partof the loop is the plot command, which plots the desired sine curves. Weinserted an echo off command so that we only see the loop commands oncein the Command Window (or in a diary file). Finally, we turn echoing back onafter exiting the loop, use hold off to tell MATLAB that the curves we justgraphed should not be held over for the next graph that we make, title thefigure, and instruct MATLAB to pause so that the viewer can see it.Pretty PrintingIf s is a symbolic expression, then typing pretty(s) displays s inpretty print format, which uses multiple lines on your screen to imitate writtenmathematics. The result is often more easily read than the default one-line out-put format. An important feature of pretty is that it wraps long expressionsto fit within the margins (80 characters wide) of a standard-sized window. Ifyour symbolic output is long enough to extend past the right edge of your win-dow, it probably will be truncated when you print your output, so you shoulduse pretty to make the entire expression visible in your printed output.A General ProcedureIn this section, we summarize the general procedure we recommend for usingthe Command Window and the Editor/Debugger (or your own text editor) tomake a calculation involving many commands. We have in mind here the casewhen you ultimately want to print your results or otherwise save them ina format you can share with others, but we find that the first steps of thisprocedure are useful even for exploratory calculations.1. Create a script M-file in your current working directory to hold your com-mands. Include echo on near the top of the file so that you can see whichcommands are producing what output when you run the M-file.2. Alternate between editing and running the M-file until you are satisfiedthat it contains the MATLAB commands that do what you want. Remem-ber to save the M-file each time between editing and running! Also, seethe debugging hints below. 46 Chapter 3: Interacting with MATLAB3. Add comments to your M-file to explain the meaning of the intermediatecalculations you do and to interpret the results.4. If desired, insert the delete and diary statements into the M-file asdescribed above.5. If you are generating graphs, add print statements that will save thegraphs to files. Use pause statements as appropriate.6. If needed, run the M-file one more time to produce the final output. Sendthe diary file and any graphics files to the printer or incorporate them intoa document.7. If you import your diary file into a word processing program, you caninsert the graphics right after the commands that generated them. Youcan also change the fonts of text comments and input to make it easierto distinguish comments, input, and output. This sort of polishing is doneautomatically by the M-book interface; see Chapter 6.Fine-Tuning Your M-FilesYou can edit your M-file repeatedly until it produces the desired output. Gene-rally, you will run the script each time you edit the file. If the program is longor involves complicated calculations or graphics, it could take a while eachtime. Then you need a strategy for debugging. Our experience indicates thatthere is no best paradigm for debugging M-files — what you do depends onthe content of your file. We will discuss features of the Editor/Debugger and MATLAB debuggingcommands in the section Debugging in Chapter 7 and in the sectionDebugging Techniques in Chapter 11. For the moment, here are some generaltips.r Include clear all and close all at the beginning of the M-file.r Use echo on early in your M-file so that you can see "cause" as well as"effect".r If you are producing graphics, use hold on and hold off carefully.In general, you should put a pause statement after each hold off.Otherwise, the next graphics command will obliterate the current one,and you won't see it.r Do not include bare print statements in your M-files. Instead, print toa file.r Make liberal use of pause. Fine-Tuning Your M-Files 47r The command keyboard is an interactive version of pause. If you havethe line keyboard in your M-file, then when MATLAB reaches it,execution of your program is interrupted, and a new prompt appearswith the letter K before it. At this point you can type any normal MATLABcommand. This is useful if you want to examine or reset some variablesin the middle of a script run. To resume the execution of your script, typereturn; i.e., type the six letters r-e-t-u-r-n and press the ENTER key.r In some cases, you might prefer input. For example, if you include theline var = input('Input var here: ') in your script, when MAT-LAB gets to that point it will print "Input var here:" and pause whileyou type the value to be assigned to var.r Finally, remember that you can stop a running M-file by typing CTRL+C.This is useful if, at a pause or input statement, you realize that youwant to stop execution completely. Algebra and Arithmetic 496. Use simplify or simple to simplify the following expressions:(a) 1/(1 + 1/(1 + 1x))(b) cos2x − sin2x7. Compute 3301, both as an approximate floating point number and as anexact integer (written in usual decimal notation).8. Use either solve or fzero, as appropriate, to solve the following equa-tions:(a) 8x + 3 = 0 (exact solution)(b) 8x + 3 = 0 (numerical solution to 15 places)(c) x3+ px + q = 0 (Solve for x in terms of p and q)(d) ex= 8x − 4 (all real solutions). It helps to draw a picture first.9. Use plot and/or ezplot, as appropriate, to graph the following functions:(a) y = x3− x for −4 ≤ x ≤ 4.(b) y = sin(1/x2) for −2 ≤ x ≤ 2. Try this one with both plot and ezplot.Are both results "correct"? (If you use plot, be sure to plot enoughpoints.)(c) y = tan(x/2) for −π ≤ x ≤ π, −10 ≤ y ≤ 10 (Hint: First draw the plot;then use axis.)(d) y = e−x2and y = x4− x2for −2 ≤ x ≤ 2 (on the same set of axes).10. Plot the functions x4and 2xon the same graph and determine how manytimes their graphs intersect. (Hint: You will probably have to make severalplots, using intervals of various sizes, to find all the intersection points.)Now find the approximate values of the points of intersection using fzero. Chapter 4Beyond the BasicsIn this chapter, we describe some of the finer points of MATLAB and review inmore detail some of the concepts introduced in Chapter 2. We explore enough ofMATLAB's internal structure to improve your ability to work with complicatedfunctions, expressions, and commands. At the end of this chapter, we introducesome of the MATLAB commands for doing calculus.Suppressing OutputSome MATLAB commands produce output that is superfluous. For example,when you assign a value to a variable, MATLAB echoes the value. You cansuppress the output of a command by putting a semicolon after the command.Here is an example:>> syms x>> y = x + 7y =x+7>> z = x + 7;>> zz =x+7The semicolon does not affect the way MATLAB processes the commandinternally, as you can see from its response to the command z.50 Data Classes 51You can also use semicolons to separate a string of commands when you areinterested only in the output of the final command (several examples appearlater in the chapter). Commas can also be used to separate commands withoutsuppressing output. If you use a semicolon after a graphics command, it willnot suppress the graphic.➱ The most common use of the semicolon is to suppress the printing ofa long vector, as indicated in Chapter 2.Another object that you may want to suppress is MATLAB's label for theoutput of a command. The command disp is designed to achieve that; typingdisp(x) will print the value of the variable x without printing the label andthe equal sign. So,>> x = 7;>> disp(x)7or>> disp(solve('x + tan(y) = 5', 'y'))-atan(x-5)Data ClassesEvery variable you define in MATLAB, as well as every input to, and outputfrom, a command, is an array of data belonging to a particular class. In thisbook we use primarily four types of data: floating point numbers, symbolicexpressions, character strings, and inline functions. We introduced each ofthese types in Chapter 2. In Table 4–1, we list for each type of data its class(as given by whos ) and how you can create it.Type of data Class Created byFloating point double typing a numberSymbolic sym using sym or symsCharacter string char typing a string inside single quotesInline function inline using inlineTable 4-1You can think of an array as a two-dimensional grid of data. A single number(or symbolic expression, or inline function) is regarded by MATLAB as a 1 × 1 52 Chapter 4: Beyond the Basicsarray, sometimes called a scalar. A 1 × n array is called a row vector, andan m× 1 array is called a column vector. (A string is actually a row vector ofcharacters.) An m× narray of numbers is called a matrix; see More on Matricesbelow. You can see the class and array size of every variable you have definedby looking in the Workspace browser or typing whos (see Managing Variablesin Chapter 2). The set of variable definitions shown by whos is called yourWorkspace.To use MATLAB commands effectively, you must pay close attention to theclass of data each command accepts as input and returns as output. The inputto a command consists of one or more arguments separated by commas; somearguments are optional. Some commands, such as whos, do not require anyinput. When you type a pair of words, such as hold on, MATLAB interpretsthe second word as a string argument to the command given by the first word;thus, hold on is equivalent to hold('on'). The help text (see Online Help inChapter 2) for each command usually tells what classes of inputs the commandexpects as well as what class of output it returns.Many commands allow more than one class of input, though sometimesonly one data class is mentioned in the online help. This flexibility can be aconvenience in some cases and a pitfall in others. For example, the integrationcommand, int, accepts strings as well as symbolic input, though its helptext mentions only symbolic input. However, suppose that you have alreadydefined a = 10, b = 5, and now you attempt to factor the expression a2− b2,forgetting your previous definitions and that you have to declare the variablessymbolic:>> factor(aˆ2 - bˆ2)ans =3 5 5The reason you don't get an error message is that factor is the name ofa command that factors integers into prime numbers as well as factoringexpressions. Since a2− b2= 75 = 3 · 52, the numerical version of factor isapplied. This output is clearly not what you intended, but in the course of acomplicated series of commands, you must be careful not to be fooled by suchunintended output. Note that typing help factor only shows you the help text for thenumerical version of the command, but it does give a cross-reference to thesymbolic version at the bottom. If you want to see the help text for thesymbolic version instead, type help sym/factor. Functions such asfactor with more than one version are called overloaded. Data Classes 53Sometimes you need to convert one data class into another to prepare theoutput of one command to serve as the input for another. For example, to useplot on a symbolic expression obtained from solve, it is convenient to usefirst vectorize and then inline, because inline does not allow symbolicinput and vectorize converts symbolic expressions to strings. You can makethe same conversion without vectorizing the expression using char. Otheruseful conversion commands we have encountered are double (symbolic tonumerical), sym (numerical or string to symbolic), and inline itself (string toinline function). Also, the commands num2str and str2num convert betweennumbers and strings.String ManipulationOften it is useful to concatenate two or more strings together. The simplest wayto do this is to use MATLAB's vector notation, keeping in mind that a string isa "row vector" of characters. For example, typing [string1, string2] com-bines string1 and string2 into one string.Here is a useful application of string concatenation. You may need to definea string variable containing an expression that takes more than one line totype. (In most circumstances you can continue your MATLAB input onto thenext line by typing ... followed by ENTER or RETURN, but this is not allowedin the middle of a string.) The solution is to break the expression into smallerparts and concatenate them, as in:>> eqn = ['left hand side of equation = ', ...'right hand side of equation']eqn =left hand side of equation = right hand side of equationSymbolic and Floating Point NumbersWe mentioned above that you can convert between symbolic numbers andfloating point numbers with double and sym. Numbers that you type are,by default, floating point. However, if you mix symbolic and floating pointnumbers in an arithmetic expression, the floating point numbers are auto-matically converted to symbolic. This explains why you can type syms x andthen xˆ2 without having to convert 2 to a symbolic number. Here is anotherexample:>> a = 1 54 Chapter 4: Beyond the Basicsa =1>> b = a/sym(2)b =1/2MATLAB was designed so that some floating point numbers are restoredto their exact values when converted to symbolic. Integers, rational numberswith small numerators and denominators, square roots of small integers, thenumber π, and certain combinations of these numbers are so restored. Forexample,>> c = sqrt(3)c =1.7321>> sym(c)ans =sqrt(3)Since it is difficult to predict when MATLAB will preserve exact values, it isbest to suppress the floating point evaluation of a numeric argument to sym byenclosing it in single quotes to make it a string, e.g., sym('1 + sqrt(3)').We will see below another way in which single quotes suppress evaluation.Functions and ExpressionsWe have used the terms expression and function without carefully making adistinction between the two. Strictly speaking, if we define f (x) = x3− 1, thenf (written without any particular input) is a function while f (x) and x3− 1are expressions involving the variable x. In mathematical discourse we oftenblur this distinction by calling f (x) or x3− 1 a function, but in MATLAB thedifference between functions and expressions is important.In MATLAB, an expression can belong to either the string or symbolic classof data. Consider the following example:>> f = 'xˆ3 - 1';>> f(7)ans =1 Functions and Expressions 55This result may be puzzling if you are expecting f to act like a function. Sincef is a string, f(7) denotes the seventh character in f, which is 1 (the spacescount). Notice that like symbolic output, string output is not indented fromthe left margin. This is a clue that the answer above is a string (consistingof one character) and not a floating point number. Typing f(5) would yield aminus sign and f(-1) would produce an error message.You have learned two ways to define your own functions, using inline (seeChapter 2) and using an M-file (see Chapter 3). Inline functions are most usefulfor defining simple functions that can be expressed in one line and for turningthe output of a symbolic command into a function. Function M-files are usefulfor defining functions that require several intermediate commands to computethe output. Most MATLAB commands are actually M-files, and you can perusethem for ideas to use in your own M-files — to see the M-file for, say, thecommand mean you can enter type mean. See also More about M-files below.Some commands, such as ode45 (a numerical ordinary differential equa-tions solver), require their first argument to be a function — to be precise,either an inline function (as in ode45(f, [0 2], 1)) or a function handle,that is, the name of a built-in function or a function M-file preceded by thespecial symbol @ (as in ode45(@func, [0 2], 1)). The @ syntax is new inMATLAB 6; in earlier versions of MATLAB, the substitute was to enclose thename of the function in single quotes to make it a string. But with or withoutquotes, typing a symbolic expression instead gives an error message. However,most symbolic commands require their first argument to be either a string ora symbolic expression, and not a function.An important difference between strings and symbolic expressions is thatMATLAB automatically substitutes user-defined functions and variables intosymbolic expressions, but not into strings. (This is another sense in which thesingle quotes you type around a string suppress evaluation.) For example, ifyou type>> h = inline('t.ˆ3', 't');>> int('h(t)', 't')ans =int(h(t),t)then the integral cannot be evaluated because within a string h is regardedas an unknown function. But if you type>> syms t>> int(h(t), t)ans =1/4*t^4 56 Chapter 4: Beyond the Basicsthen the previous definition of h is substituted into the symbolic expressionh(t) before the integration is performed.SubstitutionIn Chapter 2 we described how to create an inline function from an expression.You can then plug numbers into that function, to make a graph or table ofvalues for instance. But you can also substitute numerical values directly intoan expression with subs. For example,>> syms a x y;>> a = xˆ2 + yˆ2;>> subs(a, x, 2)ans =4+y^2>> subs(a, [x y], [3 4])ans =25More about M-FilesFiles containing MATLAB statements are called M-files. There are two kindsof M-files: function M-files, which accept arguments and produce output, andscript M-files, which execute a series of MATLAB statements. Earlier we cre-ated and used both types. In this section we present additional informationon M-files.Variables in Script M-FilesWhen you execute a script M-file, the variables you use and define belongto your Workspace; that is, they take on any values you assigned earlier inyour MATLAB session, and they persist after the script finishes executing.Consider the following script M-file, called scriptex1.m:u = [1 2 3 4];Typing scriptex1 assigns the given vector to u but displays no output. Nowconsider another script, called scriptex2.m:n = length(u) More about M-Files 57If you have not previously defined u, then typing scriptex2 will produce anerror message. However, if you type scriptex2 after running scriptex1,then the definition of u from the first script will be used in the second scriptand the output n = 4 will be displayed.If you don't want the output of a script M-file to depend on any earlier compu-tations in your MATLAB session, put the line clear all near the beginningof the M-file, as we suggested in Structuring Script M-files in Chapter 3.Variables in Function M-FilesThe variables used in a function M-file are local, meaning that they are un-affected by, and have no effect on, the variables in your Workspace. Considerthe following function M-file, called sq.m:function z = sq(x)% sq(x) returns the square of x.z = x.ˆ2;Typing sq(3) produces the answer 9, whether or not x or z is already definedin your Workspace, and neither defines them, nor changes their definitions, ifthey have been previously defined.Structure of Function M-FilesThe first line in a function M-file is called the function definition line; it definesthe function name, as well as the number and order of input and output argu-ments. Following the function definition line, there can be several commentlines that begin with a percent sign (%). These lines are called help text andare displayed in response to the command help. In the M-file sq.m above,there is only one line of help text; it is displayed when you type help sq.The remaining lines constitute the function body; they contain the MATLABstatements that calculate the function values. In addition, there can be com-ment lines (lines beginning with %) anywhere in an M-file. All statements ina function M-file that normally produce output should end with a semicolonto suppress the output.Function M-files can have multiple input and output arguments. Here isan example, called polarcoordinates.m, with two input and two outputarguments:function [r, theta] = polarcoordinates(x, y)% polarcoordinates(x, y) returns the polar coordinates% of the point with rectangular coordinates (x, y). 58 Chapter 4: Beyond the Basicsr = sqrt(xˆ2 + yˆ2);theta = atan2(y,x);If you type polarcoordinates(3,4), only the first output argument is re-turned and stored in ans; in this case, the answer is 5. To see both outputs,you must assign them to variables enclosed in square brackets:>> [r, theta] = polarcoordinates(3,4)r =5theta =0.9273By typing r = polarcoordinates(3,4) you can assign the first output ar-gument to the variable r, but you cannot get only the second output argument;typing theta = polarcoordinates(3,4) will still assign the first output,5, to theta.Complex ArithmeticMATLAB does most of its computations using complex numbers, that is, num-bers of the form a + bi, where i =√−1 and a and b are real numbers. Thecomplex number i is represented as i in MATLAB. Although you may neverhave occasion to enter a complex number in a MATLAB session, MATLABoften produces an answer involving a complex number. For example, manypolynomials with real coefficients have complex roots:>> solve('xˆ2 + 2*x + 2 = 0')ans =[ -1+i][ -1-i]Both roots of this quadratic equation are complex numbers, expressed interms of the number i. Some common functions also return complex valuesfor certain values of the argument. For example,>> log(-1)ans =0 + 3.1416i More on Matrices 59You can use MATLAB to do computations involving complex numbers by en-tering numbers in the form a + b*i:>> (2 + 3*i)*(4 - i)ans =11.0000 + 10.0000iComplex arithmetic is a powerful and valuable feature. Even if you don't in-tend to use complex numbers, you should be alert to the possibility of complex-valued answers when evaluating MATLAB expressions.More on MatricesIn addition to the usual algebraic methods of combining matrices (e.g., matrixmultiplication), we can also combine them element-wise. Specifically, if A andB are the same size, then A.*B is the element-by-element product of A and B,that is, the matrix whose i, j element is the product of the i, j elements of Aand B. Likewise, A./B is the element-by-element quotient of A and B, and A.ˆcis the matrix formed by raising each of the elements of A to the power c. Moregenerally, if f is one of the built-in functions in MATLAB, or is a user-definedfunction that accepts vector arguments, then f(A) is the matrix obtainedby applying f element-by-element to A. See what happens when you typesqrt(A), where A is the matrix defined at the beginning of the Matricessection of Chapter 2.Recall that x(3) is the third element of a vector x. Likewise, A(2,3) rep-resents the 2, 3 element of A, that is, the element in the second row and thirdcolumn. You can specify submatrices in a similar way. Typing A(2,[2 4])yields the second and fourth elements of the second row of A. To select thesecond, third, and fourth elements of this row, type A(2,2:4). The subma-trix consisting of the elements in rows 2 and 3 and in columns 2, 3, and 4 isgenerated by A(2:3,2:4). A colon by itself denotes an entire row or column.For example, A(:,2) denotes the second column of A, and A(3,:) yields thethird row of A.MATLAB has several commands that generate special matrices. The com-mands zeros(n,m) and ones(n,m) produce n × mmatrices of zeros and ones,respectively. Also, eye(n) represents the n × n identity matrix. 60 Chapter 4: Beyond the BasicsSolving Linear SystemsSuppose A is a nonsingular n × n matrix and b is a column vector of length n.Then typing x = Ab numerically computes the unique solution to A*x = b.Type help mldivide for more information.If either A or b is symbolic rather than numeric, then x = Ab computesthe solution to A*x = b symbolically. To calculate a symbolic solution whenboth inputs are numeric, type x = sym(A)b.Calculating Eigenvalues and EigenvectorsThe eigenvalues of a square matrix A are calculated with eig(A). The com-mand [U, R] = eig(A) calculates both the eigenvalues and eigenvectors.The eigenvalues are the diagonal elements of the diagonal matrix R, and thecolumns of U are the eigenvectors. Here is an example illustrating the use ofeig:>> A = [3 -2 0; 2 -2 0; 0 1 1];>> eig (A)ans =1-12>> [U, R] = eig(A)U =0 -0.4082 -0.81650 -0.8165 -0.40821.0000 0.4082 -0.4082R =1 0 00 -1 00 0 2The eigenvector in the first column of U corresponds to the eigenvaluein the first column of R, and so on. These are numerical values for theeigenpairs. To get symbolically calculated eigenpairs, type [U, R] =eig(sym(A)). Doing Calculus with MATLAB 61Doing Calculus with MATLABMATLAB has commands for most of the computations of basic calculusin its Symbolic Math Toolbox. This toolbox includes part of a separate programcalled Maple , which processes the symbolic calculations.DifferentiationYou can use diff to differentiate symbolic expressions, and also to approxi-mate the derivative of a function given numerically (say by an M-file):>> syms x; diff(xˆ3)ans =3*x^2Here MATLAB has figured out that the variable is x. (See Default Variablesat the end of the chapter.) Alternatively,>> f = inline('xˆ3', 'x'); diff(f(x))ans =3*x^2The syntax for second derivatives is diff(f(x), 2), and for nth derivatives,diff(f(x), n). The command diff can also compute partial derivativesof expressions involving several variables, as in diff(xˆ2*y, y), but to domultiple partials with respect to mixed variables you must use diff repeat-edly, as in diff(diff(sin(x*y/z), x), y). (Remember to declare y andz symbolic.)There is one instance where differentiation must be represented by theletter D, namely when you need to specify a differential equation as input toa command. For example, to use the symbolic ODE solver on the differentialequation xy + 1 = y, you enterdsolve('x*Dy + 1 = y', 'x') 62 Chapter 4: Beyond the BasicsIntegrationMATLAB can compute definite and indefinite integrals. Here is an indefiniteintegral:>> int ('xˆ2', 'x')ans =1/3*x^3As with diff, you can declare x to be symbolic and dispense with the char-acter string quotes. Note that MATLAB does not include a constant of inte-gration; the output is a single antiderivative of the integrand. Now here is adefinite integral:>> syms x; int(asin(x), 0, 1)ans =1/2*pi-1You are undoubtedly aware that not every function that appears in calcu-lus can be symbolically integrated, and so numerical integration is sometimesnecessary. MATLAB has three commands for numerical integration of a func-tion f (x): quad, quad8, and quadl (the latter is new in MATLAB 6). Werecommend quadl, with quad8 as a second choice. Here's an example:>> syms x; int(exp(-xˆ4), 0, 1)Warning: Explicit integral could not be found.> In /data/matlabr12/toolbox/symbolic/@sym/int.m at line 58ans =int(exp(-x^4),x = 0 .. 1)>> quadl(vectorize(exp(-xˆ4)), 0, 1)ans =0.8448➱ The commands quad, quad8, and quadl will not accept Inf or -Inf asa limit of integration (though int will). The best way to handle anumerical improper integral over an infinite interval is to evaluateit over a very large interval. Doing Calculus with MATLAB 63 You have another option. If you type double(int( )), then Maple'snumerical integration routine will evaluate the integral — even over aninfinite range.MATLAB can also do multiple integrals. The following command computesthe double integralπ0sin x0(x2+ y2) dy dx :>> syms x y; int(int(xˆ2 + yˆ1, y, 0, sin(x)), 0, pi)ans =pi^2-32/9Note that MATLAB presumes that the variable of integration in int is xunless you prescribe otherwise. Note also that the order of integration is as incalculus, from the "inside out". Finally, we observe that there is a numericaldouble integral command dblquad, whose properties and use we will allowyou to discover from the online help.LimitsYou can use limit to compute right- and left-handed limits and limits atinfinity. For example, here is limx→0sin(x)/x:>> syms x; limit(sin(x)/x, x, 0)ans =1To compute one-sided limits, use the 'right' and 'left' options. For exam-ple,>> limit(abs(x)/x, x, 0, 'left')ans =-1Limits at infinity can be computed using the symbol Inf:>> limit((xˆ4 + xˆ2 - 3)/(3*xˆ4 - log(x)), x, Inf)ans =1/3 64 Chapter 4: Beyond the BasicsSums and ProductsFinite numerical sums and products can be computed easily using the vectorcapabilities of MATLAB and the commands sum and prod. For example,>> X = 1:7;>> sum(X)ans =28>> prod(X)ans =5040You can do finite and infinite symbolic sums using the command symsum.To illustrate, here is the telescoping sumnk=11k−11 + k:>> syms k n; symsum(1/k - 1/(k + 1), 1, n)ans =-1/(n+1)+1And here is the well-known infinite sum∞n=11n2:>> symsum(1/nˆ2, 1, Inf)ans =1/6*pi^2Another familiar example is the sum of the infinite geometric series:>> syms a k; symsum(aˆk, 0, Inf)ans =-1/(a-1)Note, however, that the answer is only valid for |a| < 1. Default Variables 65Taylor SeriesYou can use taylor to generate Taylor polynomial expansions of a specifiedorder at a specified point. For example, to generate the Taylor polynomial upto order 10 at 0 of the function sin x, we enter>> syms x; taylor(sin(x), x, 10)ans =x-1/6*x^3+1/120*x^5-1/5040*x^7+1/362880*x^9You can compute a Taylor polynomial at a point other than the origin. Forexample,>> taylor(exp(x), 4, 2)ans =exp(2)+exp(2)*(x-2)+1/2*exp(2)*(x-2)^2+1/6*exp(2)*(x-2)^3computes a Taylor polynomial of excentered at the point x = 2.The command taylor can also compute Taylor expansions at infinity:>> taylor(exp(1/xˆ2), 6, Inf)ans =1+1/x^2+1/2/x^4Default VariablesYou can use any letters to denote variables in functions — either MATLAB'sor the ones you define. For example, there is nothing special about the use oft in the following, any letter will do as well:>> syms t; diff(sin(tˆ2))ans =2*cos(t^2)*tHowever, if there are multiple variables in an expression and you employ aMATLAB command that does not make explicit reference to one of them,then either you must make the reference explicit or MATLAB will use abuilt-in hierarchy to decide which variable is the "one in play". For example, 66 Chapter 4: Beyond the Basicssolve('x + y = 3') solves for x, not y. If you want to solve for y in thisexample, you need to enter solve('x + y = 3', 'y'). MATLAB's defaultvariable for solve is x. If there is no x in the equation(s), MATLAB looks forthe letter nearest to x in alphabetical order (where y takes precedence over w,but w takes precedence over z, etc). Similarly for diff, int, and many othersymbolic commands. Thus syms w z; diff w*z yields z as an answer. Onoccasion MATLAB assigns a different primary default variable — for example,the default independent variable for MATLAB's symbolic ODE solver dsolveis t. This is mentioned clearly in the online help for dsolve. If you have doubtabout the default variables for any MATLAB command, you should check theonline help. Chapter 5MATLAB GraphicsIn this chapter we describe more of MATLAB's graphics commands and themost common ways of manipulating and customizing them. You can get alist of MATLAB graphics commands by typing help graphics (for generalgraphics commands), help graph2d (for two-dimensional graphing), helpgraph3d (for three-dimensional graphing), or help specgraph (for special-ized graphing commands).We have already discussed the commands plot and ezplot in Chapter 2.We will begin this chapter by discussing more uses of these commands, as wellas the other most commonly used plotting commands in two and three dimen-sions. Then we will discuss some techniques for customizing and manipulatinggraphics.Two-Dimensional PlotsOften one wants to draw a curve in the x-y plane, but with y not given explicitlyas a function of x. There are two main techniques for plotting such curves:parametric plotting and contour or implicit plotting. We discuss these in turnin the next two subsections.Parametric PlotsSometimes x and y are both given as functions of some parameter. For example,the circle of radius 1 centered at (0,0) can be expressed in parametric form asx = cos(2πt), y = sin(2πt) where t runs from 0 to 1. Though y is not expressedas a function of x, you can easily graph this curve with plot, as follows:>> T = 0:0.01:1;67 68 Chapter 5: MATLAB Graphics>> plot(cos(2*pi*T), sin(2*pi*T))>> axis squareFigure 5-1The output is shown in Figure 5.1. If you had used an increment of only 0.1 inthe T vector, the result would have been a polygon with clearly visible corners,an indication that you should repeat the process with a smaller incrementuntil you get a graph that looks smooth.If you have version 2.1 or higher of the Symbolic Math Toolbox (cor-responding to MATLAB version 5.3 or higher), then parametric plotting is alsopossible with ezplot. Thus one can obtain almost the same picture as Figure5-1 with the command>> ezplot('cos(t)', 'sin(t)', [0 2*pi]); axis square Two-Dimensional Plots 69Contour Plots and Implicit PlotsA contour plot of a function of two variables is a plot of the level curves of thefunction, that is, sets of points in the x-y plane where the function assumesa constant value. For example, the level curves of x2+ y2are circles centeredat the origin, and the levels are the squares of the radii of the circles. Contourplots are produced in MATLAB with meshgrid and contour. The commandmeshgrid produces a grid of points in a specified rectangular region, with aspecified spacing. This grid is used by contour to produce a contour plot inthe specified region.We can make a contour plot of x2+ y2as follows:>> [X Y] = meshgrid(-3:0.1:3, -3:0.1:3);>> contour(X, Y, X.ˆ2 + Y.ˆ2)>> axis squareThe plot is shown in Figure 5-2. We have used MATLAB's vector notation to-3 -2 -1 0 1 2 3-3-2-10123Figure 5-2 70 Chapter 5: MATLAB Graphicsproduce a grid with spacing 0.1 in both directions. We have also used axissquare to force the same scale on both axes.You can specify particular level sets by including an additional vector ar-gument to contour. For example, to plot the circles of radii 1,√2, and√3,type>> contour(X, Y, X.ˆ2 + Y.ˆ2, [1 2 3])The vector argument must contain at least two elements, so if you wantto plot a single level set, you must specify the same level twice. This is quiteuseful for implicit plotting of a curve given by an equation in x and y. Forexample, to plot the circle of radius 1 about the origin, type>> contour(X, Y, X.ˆ2 + Y.ˆ2, [1 1])Or to plot the lemniscate x2− y2= (x2+ y2)2, rewrite the equation as(x2+ y2)2− x2+ y2= 0and type>> [X Y] = meshgrid(-1.1:0.01:1.1, -1.1:0.01:1.1);>> contour(X, Y, (X.ˆ2 + Y.ˆ2).ˆ2 - X.ˆ2 + Y.ˆ2, [0 0])>> axis square>> title('The lemniscate xˆ2-yˆ2=(xˆ2+yˆ2)ˆ2')The command title labels the plot with the indicated string. (In the defaultstring interpreter, ˆ is used for inserting an exponent and is used for sub-scripts.) The result is shown in Figure 5-3.If you have the Symbolic Math Toolbox, contour plotting can also bedone with the command ezcontour, and implicit plotting of a curve f (x, y) = 0can also be done with ezplot. One can obtain almost the same picture asFigure 5-2 with the command>> ezcontour('xˆ2 + yˆ2', [-3, 3], [-3, 3]); axis squareand almost the same picture as Figure 5-3 with the command>> ezplot('(xˆ2 + yˆ2)ˆ2 - xˆ2 + yˆ2', ...[-1.1, 1.1], [-1.1, 1.1]); axis square Two-Dimensional Plots 71Figure 5-3Field PlotsThe MATLAB routine quiver is used to plot vector fields or arrays of arrows.The arrows can be located at equally spaced points in the plane (if x and ycoordinates are not given explicitly), or they can be placed at specified loca-tions. Sometimes some fiddling is required to scale the arrows so that theydon't come out looking too big or too small. For this purpose, quiver takes anoptional scale factor argument. The following code, for example, plots a vectorfield with a "saddle point," corresponding to a combination of an attractiveforce pointing toward the x axis and a repulsive force pointing away from they axis:>> [x, y] = meshgrid(-1.1:.2:1.1, -1.1:.2:1.1);>> quiver(x, -y); axis equal; axis offThe output is shown in Figure 5-4. 72 Chapter 5: MATLAB GraphicsFigure 5-4Three-Dimensional PlotsMATLAB has several routines for producing three-dimensional plots.Curves in Three-Dimensional SpaceFor plotting curves in 3-space, the basic command is plot3, and it works likeplot, except that it takes three vectors instead of two, one for the x coordi-nates, one for the y coordinates, and one for the z coordinates. For example,we can plot a helix (see Figure 5-5) with>> T = -2:0.01:2;>> plot3(cos(2*pi*T), sin(2*pi*T), T)Again, if you have the Symbolic Math Toolbox, there is a shortcutusing ezplot3; you can instead plot the helix with>> ezplot3('cos(2*pi*t)', 'sin(2*pi*t)', 't', [-2, 2]) Three-Dimensional Plots 73-1-0.500.51-1-0.500.51-2-1.5-1-0.500.511.52Figure 5-5Surfaces in Three-Dimensional SpaceThere are two basic commands for plotting surfaces in 3-space: mesh andsurf. The former produces a transparent "mesh" surface; the latter producesan opaque shaded one. There are two different ways of using each command,one for plotting surfaces in which the z coordinate is given as a function of xand y, and one for parametric surfaces in which x, y, and z are all given asfunctions of two other parameters. Let us illustrate the former with mesh andthe latter with surf.To plot z = f (x, y), one begins with a meshgrid command as in the case ofcontour. For example, the "saddle surface" z = x2− y2can be plotted with>> [X,Y] = meshgrid(-2:.1:2, -2:.1:2);>> Z = X.ˆ2 - Y.ˆ2;>> mesh(X, Y, Z)The result is shown in Figure 5-6, although it looks much better on the screensince MATLAB shades the surface with a color scheme depending on the zcoordinate. We could have gotten an opaque surface instead by replacing meshwith surf. 74 Chapter 5: MATLAB Graphics-2-1012-2-1012-4-3-2-101234Figure 5-6With the Symbolic Math Toolbox, there is a shortcut command ezmesh,and you can obtain a result very similar to Figure 5-6 with>> ezmesh('xˆ2 - yˆ2', [-2, 2], [-2, 2])If one wants to plot a surface that cannot be represented by an equationof the form z = f (x, y), for example the sphere x2+ y2+ z2= 1, then it is bet-ter to parameterize the surface using a suitable coordinate system, in thiscase cylindrical or spherical coordinates. For example, we can take as param-eters the vertical coordinate z and the polar coordinate θ in the x-y plane. Ifr denotes the distance to the z axis, then the equation of the sphere becomesr2+ z2= 1, or r =√1 − z2, and so x =√1 − z2 cos θ, y =√1 − z2 sin θ. Thuswe can produce our plot with>> [theta, Z] = meshgrid((0:0.1:2)*pi, (-1:0.1:1));>> X = sqrt(1 - Z.ˆ2).*cos(theta); Special Effects 75-1-0.500.51-1-0.500.51-1-0.500.51Figure 5-7>> Y = sqrt(1 - Z.ˆ2).*sin(theta);>> surf(X, Y, Z); axis squareThe result is shown in Figure 5-7.With the Symbolic Math Toolbox, parametric plotting of surfaces hasbeen greatly simplified with the commands ezsurf and ezmesh, and you canobtain a result very similar to Figure 5-7 with>> ezsurf('sqrt(1-sˆ2)*cos(t)', 'sqrt(1-sˆ2)*sin(t)', ...'s', [-1, 1, 0, 2*pi]); axis equalSpecial EffectsSo far we have only discussed graphics commands that produce or modify asingle static figure window. But MATLAB is also capable of combining several 76 Chapter 5: MATLAB Graphicsfigures in one window, or of producing animated graphics that change withtime.Combining Figures in One WindowThe command subplot divides the figure window into an array of smallerfigures. The first two arguments give the dimensions of the array of sub-plots, and the last argument gives the number of the subplot (counting leftto right across the first row, then left to right across the next row, and so on)in which to put the next figure. The following example, whose output appearsas Figure 5-8, produces a 2 × 2 array of plots of the first four Bessel functionsJn, 0 ≤ n ≤ 3:>> x = 0:0.05:40;>> for j = 1:4, subplot(2,2,j)plot(x, besselj(j*ones(size(x)), x))end0 10 20 30 40-0.500.510 10 20 30 40-0.4-0.200.20.40.60 10 20 30 40-0.4-0.200.20.40.60 10 20 30 40-0.4-0.200.20.40.6Figure 5-8 Special Effects 77AnimationsThe simplest way to produce an animated picture is with comet, which pro-duces a parametric plot of a curve (the way plot does), except that you cansee the curve being traced out in time. For example,>> t = 0:0.01*pi:2*pi;>> figure; axis equal; axis([-1 1 -1 1]); hold on>> comet(cos(t), sin(t))displays uniform circular motion.For more complicated animations, you can use getframe and movie. Thecommand getframe captures the active figure window for one frame of themovie, and movie then plays back the result. For example, the following (inMATLAB 5.3 or later — earlier versions of the software used a slightly differ-ent syntax) produces a movie of a vibrating string:>> x = 0:0.01:1;>> for j = 0:50plot(x, sin(j*pi/5)*sin(pi*x)), axis([0, 1, -2, 2])M(j+1) = getframe;end>> movie(M)It is worth noting that the axis command here is important, to ensure thateach frame of the movie is drawn with the same coordinate axes. (Other-wise the scale of the axes will be different in each frame and the result-ing movie will be totally misleading.) The semicolon after the getframecommand is also important; it prevents the spewing forth of a lot of nu-merical data with each frame of the movie. Finally, make sure that whileMATLAB executes the loop that generates the frames, you do not cover theactive figure window with another window (such as the Command Window).If you do, the contents of the other window will be stored in the frames of themovie. MATLAB 6 has a new command movieview that you can use in place ofmovie to view the animation in a separate window, with a button to replaythe movie when it is done. 78 Chapter 5: MATLAB GraphicsCustomizing and ManipulatingGraphics This is a more advanced topic; if you wish you can skip it on a first reading.So far in this chapter, we have discussed the most commonly used MATLABroutines for generating plots. But often, to get the results one wants, one needsto customize or manipulate the graphics these commands produce. Knowinghow to do this requires understanding a few basic principles concerning theway MATLAB stores and displays graphics. For most purposes, the discussionhere will be sufficient. But if you need more information, you might eventuallywant to consult one of the books devoted exclusively to MATLAB graphics,such as Using MATLAB Graphics, which comes free (in PDF format) withthe software and can be accessed in the "MATLAB Manuals" subsection ofthe "Printable Documentation" section in the Help Browser (or under "FullDocumentation Set" from the helpdesk in MATLAB 5.3 and earlier versions),or Graphics and GUIs with MATLAB, 2nd ed., by P. Marchand, CRC Press,Boca Raton, FL, 1999.In a typical MATLAB session, one may have many figure windows openat once. However, only one of these can be "active" at any one time. One canfind out which figure is active with the command gcf, short for "get currentfigure," and one can change the active figure to, say, figure number 5 with thecommand figure(5), or else by clicking on figure window 5 with the mouse.The command figure (with no arguments) creates a blank figure window.(This is sometimes useful if you want to avoid overwriting an existing plot.)Once a figure has been created and made active, there are two basic ways tomanipulate it. The active figure can be modified by MATLAB commands in thecommand window, such as the commands title and axis square that wehave already encountered. Or one can modify the figure by using the menusand/or tools in the figure window itself. Let's consider a few examples. To insertlabels or text into a plot, one may use the commands text, xlabel, ylabel,zlabel, and legend, in addition to title. As the names suggest, xlabel,ylabel, and zlabel add text next to the coordinate axes, legend puts a"legend" on the plot, and text adds text at a specific point. These commandstake various optional arguments that can be used to change the font familyand font size of the text. As an example, let's illustrate how to modify our plotof the lemniscate (Figure 5-3) by adding and modifying text:>> figure(3)>> title('The lemniscate xˆ2-yˆ2=(xˆ2+yˆ2)ˆ2',... Customizing and Manipulating Graphics 79← a node, also an inflectionpoint for each branchxyFigure 5-9'FontSize', 16, 'FontName', 'Helvetica',...'FontWeight', 'bold')>> text(0, 0, 'leftarrow a node, also an inflection')>> text(0.2, -0.1, 'point for each branch')>> xlabel('x'); ylabel('y')The result is shown in Figure 5-9. Note that many symbols (an arrow pointingto the left in this case) can be inserted into a text string by calling themwith names starting with . (If you've used the scientific typesetting programTEX, you'll recognize the convention here.) In most cases the names are self-explanatory. For example, you get a Greek π by typing pi, a summation signby typing either Sigma (for a capital sigma) or sum, and arrows pointingin various directions with leftarrow, uparrow, and so on. For more detailsand a complete list of available symbols, see the listing for "Text Properties"in the Help Browser.An alternative is to make use of the tool bar at the top of the figure window.The button indicated by the letter "A" adds text to a figure, and the menu item 80 Chapter 5: MATLAB GraphicsText Properties... in the Tools menu (in MATLAB 5.3), or else the menuitem Figure Properties... in the Edit menu (in MATLAB 6), can be used tochange the font style and font size.Change of ViewpointAnother common and important way to vary a graphic is to change the view-point in 3-space. This can be done with the command view, and also (at leastin MATLAB 5.3 and higher) by using the Rotate 3D option in the Tools menuat the top of the figure window. The command view(2) projects a figure intothe x-y plane (by looking down on it from the positive z axis), and the com-mand view(3) views it from the default direction in 3-space, which is in thedirection looking toward the origin from a point far out on the ray z = 0.5t,x = −0.5272t, y = −0.3044t, t > 0.➱ In MATLAB, any two-dimensional plot can be "viewed in 3D," andany three-dimensional plot can be projected into the plane. ThusFigure 5-5 above (the helix), if followed by the command view(2),produces a circle.Change of Plot StyleAnother important way to change the style of graphics is to modify the color orline style in a plot or to change the scale on the axes. Within a plot command,one can change the color of a graph, or plot with a dashed or dotted line, ormark the plotted points with special symbols, simply by adding a string as athird argument for every x-y pair. Symbols for colors are 'y' for yellow, 'm'for magenta, 'c' for cyan, 'r' for red, 'g' for green, 'b' for blue, 'w' forwhite, and 'k' for black. Symbols for point markers include 'o' for a circle,'x' for an X-mark, '+' for a plus sign, and '*' for a star. Symbols for linestyles include '-' for a solid line, ':' for a dotted line, and '--' for a dashedline. If a point style is given but no line style, then the points are plotted butno curve is drawn connecting them. The same methods work with plot3 inplace of plot. For example, one can produce a solid red sine curve along with adotted blue cosine curve, marking all the local maximum points on each curvewith a distinctive symbol of the same color as the plot, as follows:>> X = (-2:0.02:2)*pi; Y1 = sin(X); Y2 = cos(X);>> plot(X, Y1, 'r-', X, Y2, 'b:'); hold on>> X1 = [-3*pi/2 pi/2]; Y3 = [1 1]; plot(X1, Y3, 'r+')>> X2 = [-2*pi 0 2*pi]; Y4 = [1 1 1]; plot(X2, Y4, 'b*') Customizing and Manipulating Graphics 81Here we would probably want the tick marks on the x axis located at mul-tiples of π. This can be done with the set command applied to the propertiesof the axes (and/or by selecting Edit : Axes Properties... in MATLAB 6,or Tools : Axes Properties... in MATLAB 5.3). The command set is usedto change various properties of graphics. To apply it to "Axes", it has to becombined with the command gca, which stands for "get current axes". Thecode>> set(gca, 'XTick', (-2:2)*pi, 'XTickLabel',...'-2pi|-pi|0|pi|2pi')in combination with the code above gets the current axes, sets the ticks onthe x axis to go from −2π to 2π in multiples of π, and then labels these ticksthe way one would want (rather than in decimal notation, which is ugly here).The result is shown in Figure 5-10. Incidentally, you might wonder how to labelthe ticks as −2π, −π, etc., instead of -2pi, -pi, and so on. This is trickier butyou can do it by typing-2pi -pi 0 pi 2pi-1-0.8-0.6-0.4-0.200.20.40.60.81Figure 5-10 82 Chapter 5: MATLAB Graphics>> set(gca, 'FontName', 'Symbol')>> set(gca, 'XTickLabel', '-2p|-p|0|p|2p')since in the Symbol font, π occupies the slot held by p in text fonts.Full-Fledged CustomizationWhat about changes to other aspects of a plot? The useful commands get andset can be used to obtain a complete list of the properties of a graphics window,and then to modify them. These properties are arranged in a hierarchicalstructure, identified by markers (which are simply numbers) called handles.If you type get(gcf), you will "get" a (rather long) list of properties of thecurrent figure (whose number is returned by the function gcf). Some of thesemight readColor = [0.8 0.8 0.8]CurrentAxes = [72.0009]PaperSize = [8.5 11]Children = [72.0009]Here PaperSize is self-explanatory; Color gives the background color of theplot in RGB (red-green-blue) coordinates, where [0 0 0] is black and [1 1 1]is white. ([0.8 0.8 0.8] is light gray.) Note that CurrentAxes and Childrenin this example have the same value, the one-element vector containing thefunny-looking number 72.0009. This number would also be returned by thecommand gca ("get current axes"); it is the handle to the axis properties ofthe plot. The fact that this also shows up under Children indicates that theaxis properties are "children" of the figure, this is, they lie one level down in thehierarchical structure. Typing get(gca) or get(72.0009) would then giveyou a list of axis properties, including further Children such as Line objects,within which you would find the XData and YData encoding the actual plot.Once you have located the properties you're interested in, they can bechanged with set. For example,>> set(gcf, 'Color', [1 0 0])changes the background color of the border of the figure window to red, and>> set(gca, 'Color', [1 1 0])changes the background color of the plot itself (a child of the figure window)to yellow (which in the RGB scheme is half red, half green). Customizing and Manipulating Graphics 83This "one at a time" method for locating and modifying figure propertiescan be speeded up using the command findobj to locate the handles of allthe descendents (the main figure window, its children, children of children,etc.) of the current figure. One can also limit the search to handles containingelements of a specific type. For example, findobj('Type', 'Line') huntsfor all handles of objects containing a Line element. Once one has locatedthese, set can be used to change the LineStyle from solid to dashed, etc.In addition, the low-level graphics commands line, rectangle, fill,surface, and image can be used to create new graphics elements within afigure window.As an example of these techniques, the following code creates a chessboardon a white background, as shown in Figure 5-11:>> white = [1 1 1]; gray = 0.7*white;>> a = [0 1 1 0]; b = [0 0 1 1]; c = [1 1 1 1];Figure 5-11 84 Chapter 5: MATLAB Graphics>> figure; hold on>> for k = 0:1, for j = 0:2:6fill(a'*c + c'*(0:2:6) + k, b'*c + j + k, gray)end, end>> plot(8*a', 8*b', 'k')>> set(gca, 'XTickLabel', [], 'YTickLabel', [])>> set(gcf, 'Color', white); axis squareHere white and gray are the RGB codings for white and gray. The doublefor loop draws the 32 dark squares on the chessboard, using fill, with jindexing the dark squares in a single vertical column, with k = 0 giving theodd-numbered rows, and with k = 1 giving the even-numbered rows. Notethat fill here takes three arguments: a matrix, each of whose columns givesthe x coordinates of the vertices of a polygon to be filled (in this case a square),a second matrix whose corresponding columns give the y coordinates of thevertices, and a color. We've constructed the matrices with four columns, onefor each of the solid squares in a single horizontal row. The plot commanddraws the solid black line around the outside of the board. Finally, the firstset command removes the printed labels on the axes, and the second setcommand resets the background color to white.Quick Plot Editing in the Figure WindowAlmost all of the command-line changes one can make in a figure have coun-terparts that can be executed using the menus in the figure window. So whybother learning both techniques? The reason is that editing in the figure win-dow is often more convenient, especially when one wishes to "experiment" withvarious changes, while editing a figure with MATLAB code is often requiredwhen writing M-files. So the true MATLAB expert uses both techniques. Thefigure window menus are a bit different in MATLAB 6 than in MATLAB 5.3.In MATLAB 6, you can zoom in and out and rotate the figure using the Toolsmenu, you can insert labels and text with the Insert menu, and you can viewand edit the figure properties (just as you would with set) with the Editmenu. For example you can change the ticks and labels on the axes by se-lecting Edit : Edit Axes.... In MATLAB 5.3, editing of the figure properties isdone with the Property Editor, located under the File menu of the figurewindow. By default this opens to the figure properties, and double-clicking on"Children" then enables you to access the axes properties, etc. Sound 85SoundYou can use sound to generate sound on your computer (provided that yourcomputer is suitably equipped). Although, strictly speaking, sound is not agraphics command, we have placed it in this chapter since we think of "sight"and "sound" as being allied features. The command sound takes a vector, viewsit as the waveform of a sound, and "plays" it. The length of the vector, divided by8192, is the length of the sound in seconds. A "sinusoidal" vector correspondsto a pure tone, and the frequency of the sinusoidal signal determines the pitch.Thus the following example plays the motto from Beethoven's 5th Symphony:>> x=0:0.1*pi:250*pi; y=zeros(1,200); z=0:0.1*pi:1000*pi;>> sound([sin(x),y,sin(x),y,sin(x),y,sin(z*4/5),y,...sin(8/9*x),y,sin(8/9*x),y,sin(8/9*x),y,sin(z*3/4)]);Note that the zero vector y in this example creates a very short pause betweensuccessive notes. 88 Practice Set B: Calculus, Graphics, and Linear Algebra(b) Now try the same method on Problem 4 of Practice Set A. MATLABfinds one, but not all, answer(s). Can you explain why? If not, seeProblem 11 below, as well as part (d) of this problem.(c) Next try the method on this problem:w + 3x − 2y + 4z = 1−2w + 3x + 4y − z = 1−4w − 3x + y + 2z = 12w + 3x − 4y + z = 1.Check your answer by matrix multiplication.(d) Finally, try the matrix division method on:ax + by = ucx + dy = v.Don't forget to declare the variables to be symbolic. Your answershould involve a fraction, and so will be valid only when its de-nominator is nonzero. Evaluate det on the coefficient matrix of thesystem. Compare with the denominator.11. We deal in this problem with 3 × 3 matrices, although the concepts arevalid in any dimension.(a) Consider the rows of a square matrix A. They are vectors in 3-spaceand so span a subspace of dimension 3, 2, 1, or possibly 0 (if allthe entries of A are zero). That number is called the rank of A. TheMATLAB command rank computes the rank of a matrix. Try iton the four coefficient matrices in each of the parts of Problem 10.Comment on MATLAB's answer for the fourth one.(b) An n × n matrix is nonsingular if its rank is n. Which of the fourmatrices you computed in part (a) are nonsingular?(c) Another measure of nonsingularity is given by the determinant — afundamental result in linear algebra is that a matrix is nonsingularprecisely when its determinant is nonzero. In that case a uniquematrix B exists that satisfies AB = BA = the identity matrix. Wedenote this inverse matrix by A−1. MATLAB can compute inverseswith inv. Compute det(A) for the four coefficient matrices, and forthe nonsingular ones, find their inverses. Note: The matrix equationAx = b has a unique solution, namely x = A−1b = Ab, when A isnonsingular.12. As explained in Chapter 4, when you compute [U, R] = eig(A), eachcolumn of U is an eigenvector of A associated to the eigenvalue that Practice Set B: Calculus, Graphics, and Linear Algebra 89appears in the corresponding column of the diagonal matrix R. This saysexactly that AU = UR.(a) Verify the equality AU = UR for each of the coefficient matrices inProblem 10.(b) In fact, rank(A) = rank(U), so when A is nonsingular, thenU−1AU = R.Thus if two diagonalizable matrices A and B have the same set ofeigenvectors, then the fact that diagonal matrices commute impliesthe same for A and B. Verify these facts for the two matricesA =1 0 2−1 0 4−1 −1 5 , B =5 2 −83 6 −103 3 −7 ;that is, show that the matrices of eigenvectors are the "same" —that is, the columns are the same up to scalar multiples — andverify that AB = BA.13. This problem, having to do with genetic inheritance, is based on Chapter12 in Applications of Linear Algebra, 3rd ed., by C. Rorres and H. Anton,John Wiley & Sons, 1984. In a typical inheritance model, a trait in the off-spring is determined by the passing of a genotype from the parents, wherethere are two independent possibilities from each parent, say A and a,and each is equally likely. (A is the dominant gene, and a is recessive.)Then we have the following table of probabilities of the possible geno-types for the offspring for all possible combinations of the genotypes of theparents:Genotype of ParentsAA-AA AA-Aa AA-aa Aa-Aa Aa-aa aa-aaGenotype AA 1 1/2 0 1/4 0 0of Aa 0 1/2 1 1/2 1/2 0Offspring aa 0 0 0 1/4 1/2 1Now suppose one has a population in which mating only occurs withone's identical genotype. (That's not far-fetched if we are considering con-trolled plant or vegetable populations.) Next suppose that x0, y0, and z0denote the percentage of the population with genotype AA, Aa, and aarespectively at the outset of observation. We then denote by xn, yn, andzn the percentages in the nth generation. We are interested in knowing 90 Practice Set B: Calculus, Graphics, and Linear Algebrathese numbers for large n and how they depend on the initial population.Clearlyxn + yn + zn = 1, n ≥ 0.Now we can use the table to express a relationship between the nth and(n + 1)st generations. Because of our presumption on mating, only the first,fourth, and sixth columns are relevant. Indeed a moment's reflection re-veals that we havexn+1 = xn +14ynyn+1 =12yn (*)zn+1 = zn +14yn.(a) Write the equations (*) as a single matrix equation Xn+1 = MXn,n ≥ 0. Explain carefully what the entries of the column matrix Xnare and what the coefficients of the square matrix M are.(b) Apply the matrix equation recursively to express Xn in terms of X0and powers of M.(c) Next use MATLAB to compute the eigenvalues and eigenvectors ofM.(d) From Problem 12 you know that MU = UR, where R is the diag-onal matrix of eigenvalues of M. Solve that equation for M. Nowit should be evident to you what R∞ = limn→∞ Rnis. Use that andyour expression of M in terms of R to compute M∞ = limn→∞ Mn.(e) Describe the eventual population distribution by computing M∞ X0.(f) Check your answer by directly computing Mnfor large specific val-ues of M. (Hint: MATLAB can compute the powers of a matrix M byentering Mˆ10, for example.)(g) You can alter the fundamental presumption in this problem by as-suming, alternatively, that all members of the nth generation mustmate only with a parent whose genotype is purely dominant. Com-pute the eventual population distribution of that model. Chapters12–14 in Rorres and Anton have other interesting models. Chapter 6M-BooksMATLAB is exceptionally strong in linear algebra, numerical methods, andgraphical interpretation of data. It is easily programmed and relatively easyto learn to use. As such it has proven invaluable to engineers and scientistswho are working on problems that rely on scientific techniques and methods atwhich MATLAB excels. Very often the individuals and groups that so employMATLAB are primarily interested in the numbers and graphs that emergefrom MATLAB commands, processes, and programs. Therefore, it is enoughfor them to work in a MATLAB Command Window, from which they can eas-ily print or export their desired output. At most, the production techniquedescribed in Chapter 3 involving diary files is sufficient for their presentationneeds.However, other practitioners of mathematical software find themselves withtwo additional requirements. They need a mathematical software package em-bedded in an interactive environment — one in which the output is not nec-essarily "linear", that is, one that they can manipulate and massage withoutregard to chronology or geographical location. Second, they need a higher-levelpresentation mode, which affords graphics integrated with text, with differentformats for input and output, and one that can communicate effortlessly withother software applications. Some of MATLAB's competitors have focused onsuch needs in designing the interfaces (or front ends) behind which their math-ematical software runs. MATLAB has decided to concentrate on the softwarerather than the interface — and for the reasons and purposes outlined above,that is clearly a wise decision. But for academic users (both faculty and espe-cially students), for authors, and even for applied scientists who want to useMATLAB to generate slick presentations, the interface demands can becomevery important. For them, MATLAB has provided the M-book interface, whichwe describe in this chapter.91 92 Chapter 6: M-BooksThe M-book interface allows the user to operate MATLAB from a specialMicrosoft Word document instead of from a MATLAB Command Window. Inthis mode, the user should think of Word as running in the foreground andMATLAB as running in the background. Lines that you enter into your Worddocument are passed to the MATLAB engine in the background and executedthere, whereupon the output is returned to Word (through the intermediary ofVisual Basic ), and then both input and output are automatically formatted.One obtains a living document in the sense that one can edit the document asone normally edits a word processing document. So one can revisit input linesthat need adjustment, change them, and reexecute on the spot — after whichthe old outdated output is automatically overwritten with new output. Thegraphical output that results from MATLAB graphics commands appear inthe Word document, immediately after the commands that generated them.Erroneous input and output are easily expunged, enhanced formatting canbe done in a way that is no more complicated than what one does in a wordprocessor, and in the end the result of your MATLAB session can be an at-tractive, easily readable, and highly informative document. Of course, one can"cheat" by editing one's output — we shall discuss that and other pitfalls andstrengths in what follows.Enabling M-BooksTo run the M-book interface you must have Microsoft Word on your com-puter. It is possible to run the interface with earlier versions of Word, butwe find that it works best if you have Word 97. (In fact, we find that itruns better in Word 97 than it does in Word 2000, though the difference isnot usually significant.) The interface is enabled when you install MATLAB.This is done in one of three ways depending on which version of MATLAByou have. In some instances, during installation, you will be prompted toenter the location of the Word executable file and the Word template direc-tory. These are usually easily located; for example, on many PCs the formeris in MSOfficeOfficeWinword.exe, and the latter is in MSOfficeTemplates. You may also be asked to specify a template file — in that case,select normal.dot in the Templates directory. The installation program willcreate a new template called m-book.dot, which is the Word template file as-sociated with M-book documents. If you don't know where the Word files are located on your PC, go to Findfrom the Start menu on the Task Bar, and search your hard drive for thefiles Winword.exe and normal.dot. Starting M-Books 93In other instances, you may not notice any prompt for Word informationduring installation. This can mean that your computer found the Wordexecutable and template information and set up the associations automat-ically; or it can mean that it ignored the M-book configuration completely.In either eventuality, it is best, after installation, to type notebook -setupfrom the Command Window. Follow the ensuing instructions, which will beessentially the same as in the first possibility described in the last paragraph.Starting M-BooksThe most common way to start up the M-book interface is to type notebookat the Command Window prompt. This is the only way to start the M-bookinterface if it is your first foray into the venue. After you type notebook,you will see Microsoft Word launch and a blank Word document will fill yourscreen. We will refer to this document as an M-book. The difference between ablank M-book and a normal Word document is only apparent if you peruse themenu bar. There you will see an entry that is not present in a normal Worddocument — namely, the Notebook menu. Click on it and examine the menuitems that appear. We will describe each of them and their functions in ourdiscussion below. If this is not your first experience with M-books, and youhave already saved an M-book, say under the name Problem1.doc, then youcan open it by typing notebook Problem1.doc at the Command Windowprompt. Even though you may not see it, the MATLAB Command Window isalive, but it is hidden behind the M-book.➱ On some systems, you may see a DOS command window appear aftertyping notebook, but before the M-book appears. We recommendthat you close that window before working in the M-book. For M-books to work properly, you need to have "Macros Enabled" in yourWord installation. If an M-book opens as a regular Word document, withoutM-book functionality, it probably means that macros have been disabled. Toenable them, first close the document (without saving changes), then go toTools : Macro : Security... from the Word menu bar, and reset your securitylevel to Medium or Low. Then reopen the M-book. An alternate, and on some systems (especially networked systems) apreferable, launch method is first to open a previously saved M-book —either directly through File : Open... in Word or by double-clicking on thefile name in Windows Explorer. Word recognizes that the document is anM-book, so automatically launches MATLAB if it is not already running. A 94 Chapter 6: M-Booksword of caution: If you have more than one version of MATLAB installed,Word will launch the version you installed last. To override this, you canopen the MATLAB version you want before you open the M-book.You can now type into the M-book in the usual way. In fact you could pre-pare a document in this screen in precisely the same manner that you wouldin a normal Word screen. The background features of MATLAB are only ac-tivated if you do one of two things: either access the items in the Notebookmenu or press the key combination CTRL+ENTER. Type into your M-book theline 23/45 and press CTRL+ENTER. After a short delay you will see what youentered change font to bold New Courier, encased in brackets, and then theoutputans =0.5111will appear below, also in New Courier font (but not bold). It is also likely thatthe input and output will be colored (the input in green, the output in blue).Your cursor should be on the line following the output, but if it is at the endof the output line, move it down a line and type solve('xˆ2 - 5*x + 5 =0') followed by CTRL+ENTER. After some thought MATLAB feeds the answerto the M-book:ans=[5/2+1/2*5^(1/2)][5/2-1/2*5^(1/2)]Finally, try typing ezplot('xˆ3 - x'), then CTRL+ENTER, and watch thegraph appear. At this point your M-book should look like Figure 6-1.You may note that your commands take a little longer to evaluate thanthey would inside a normal MATLAB Command Window. This is not sur-prising considering the amount of information that is passing back and forthbetween MATLAB and Word. Continue entering MATLAB commands that arefamiliar to you (always followed by CTRL+ENTER), and observe that you obtainthe output you expect, except that it is formatted and integrated into yourM-book. If you want to start a fresh M-book, click on File : New M-book in the MenuBar, or File : New, and then click on m-book.dot. Working with M-Books 95Figure 6-1: A Simple M-Book.Working with M-BooksYou interact with data in your M-book in two ways — via the keyboard orthrough the menu bar.Editing InputPlace your cursor in the line containing the second command of the previoussection — where we solved the quadratic equationx2− 5x + 5 = 0.Click to the left of the equal sign, hit BACKSPACE, type 6 (that is, replace thesecond 5 by a 6), and press CTRL+ENTER. You will see your output replaced byans =[ 2][ 3]By changing the quadratic equation we have altered its roots. You can editany of the input lines in your M-book in this way, including the one thatgenerated the graph. See what happens if you click in the ezplot commandline, change the cubic expression, and press CTRL+ENTER. 96 Chapter 6: M-BooksIt is important to understand that your M-book can be handled in exactlythe same way that you would any Word document. In particular, you cansave the file, print the document, change fonts or margins, move or export agraphic, etc. This has the advantage of allowing you to present the resultsof your MATLAB session in an attractively formatted style. It also has thedisadvantage of affording the user the opportunity to muck with MATLAB'sinput or output and so to create input and output that may not truly correspondto each other. One must be very careful! Note that the help item on the menu bar is Word help, not MATLAB help. Ifyou want to invoke MATLAB help, then either type help (with CTRL+ENTERof course) or bring the MATLAB Command Window to the foreground (seebelow) and use MATLAB help in the usual fashion.The Notebook MenuNext let's examine the items in the Notebook menu. First comes DefineInput Cell. If you put your cursor on any line and select Define Input Cell,then that line will become an input line. But to evaluate it, you still need topress CTRL+ENTER. The advantage to this item is apparent when you want tocreate an input cell containing more than one line. For example, typesyms x yfactor(xˆ2 - yˆ2)and then select both lines (by clicking and dragging over them) and chooseDefine Input Cell. CTRL+ENTER will then cause both lines to be evaluated. Youcan recognize that both lines are incorporated into one input cell by looking atthe brackets, or Cell Markers. The menu item Hide Cell Markers will causethe Cell Markers to disappear; in fact that menu item is a toggle switch thatturns the Markers on and off. If you have several input cells, you can convertthem into one input cell by selecting them and choosing Group Cells. You canbreak them apart by choosing Ungroup Cells. If you click in an input celland choose Undefine Cells, that cell ceases to be an input cell; its formattingreverts to the default Word format, as does the corresponding output cell. Ifyou "undefine" an output cell, it loses its format, but the corresponding inputcell remains unchanged.If you select some portion of your M-book (for example, the entire M-bookby using Edit : Select All) and then choose Purge Output Cells, all outputcells in the selection will be deleted. This is particularly useful if you wishto change some data on which the output in your selection depends, and then M-Book Graphics 97reevaluate the entire selection by choosing Evaluate Cell. You can reevaluatethe entire M-book at any time by choosing Evaluate M-book. If your M-bookcontains a loop, you can evaluate it by selecting it and choosing EvaluateLoop, or for that matter Evaluate Cell, provided the entire loop is inside asingle input cell.It is often handy to purge all output from an M-book before saving, toeconomize on storage space or on time upon reopening, especially if thereare complicated graphs in the document. If there are any input cells that youwant to automatically evaluate upon opening of the M-book, select them andclick on Define Auto Init Cell. The color of the text in those cells will change.If you want to separate out a series of commands, say for repeated evaluation,then select the cells and click on Define Calc Zone. The commands selectedwill be encased in a Word section (with section breaks before and after it). Ifyou click in the section and select Evaluate Calc Zone from the Notebookmenu, the commands in only that zone will be (re)evaluated.The last two buttons are also useful. The button Bring MATLAB to Frontdoes exactly that; it reveals the MATLAB Command Window that has beenhiding behind the M-book. You may want to enter a command directly into theCommand Window (for example, a help entry) and not have it in your M-book.Finally, the last button, Notebook Options brings up a panel in which youcan do some customization of your M-book: set the numerical format, establishthe size of graphics figures, etc. We find it most useful to decrease the defaultgraphics size — the "factory setting" is generally too large. Decreasing thefigure size with Notebook Options may not work with Word 2000, though itis still possible to change the size of figures one at a time, by right clicking onthe figure and then choosing the "Size" tab from Format Object....M-Book GraphicsAll MATLAB commands that generate graphics work in M-books. The figureproduced by a graphics command appears immediately below that command.However, one must be a little careful in planning and executing graphicsstatements. For example, if in an attempt to reproduce Figure 5-3, you typeezcontour('xˆ2 + yˆ2', [-3 3], [-3 3]) and CTRL+ENTER, this willyield the level curves of x2+ y2, but they will appear elliptical because youforgot the command axis square. If you enter that command on the nextline, you will get a second picture that will be correct. But a much betterstrategy — and one that we strongly recommend — is to return to the originalinput cell and edit it by adding a semicolon (or a carriage return) and the axis 98 Chapter 6: M-Bookssquare statement. In general, as you refine your graphics in an M-book, youwill find it is more desirable to modify the input cells that generated them,rather than to produce more pictures by repeating the command with newoptions. So when adding things such as xlabel, ylabel, legend, title,etc., it is usually best to just add them to the graphics input cell and reevalu-ate. As a result, input cells generating graphics in M-books often end up beingseveral lines long.In instances where you really do want to generate a new picture, then youneed to think about whether you want to have hold set to on or off. Thisfeature works exactly as in a Command Window — if hold is set to on, what-ever graphic results from your next command will be combined with whateverlast graphic you produced; and if hold is off, then previous graphics will notinfluence any graphic you generate.Since there are no separate graphics windows, the command figure is oflimited use in M-books; you probably should not use it. If you do, it will producea blank graph. Similarly, there are other graphics commands that are not sosuitable for use in M-books, for example close. There is one exception to this rule: Sometimes you might want to use afigure window along with an M-book, for example to rotate a plot with themouse. If you type figure from the Command Window to open a figurewindow, then subsequent graphics from the M-book will appearsimultaneously in the figure window and in the M-book itself.Finally, we note the button Toggle Graph Output for Cell, the only buttonon the Notebook menu not previously described. If you select a cell contain-ing a graphics command and click on this button, no graphical output willresult from the evaluation of this command. This can be useful when usedin conjunction with hold on if you want to produce a single graphic usingmultiple command lines.More Hints for Effective Use of M-BooksIf an interactive mode and/or attractive output beyond what you can achievewith M-files and diary files is your goal, then you should get used to working inthe M-book interface rather than in a Command Window. Even experiencedMATLAB users will find that in time they will get use to the environment.Here are a few more hints to smooth your transition.In Chapter 3 we outlined some strategies for effective use of M-files, es-pecially in the realm of debugging. Many of the techniques we described are A Warning 99unnecessary in the M-book mode. For example, the commands pause andkeyboard serve no purpose. In addition the UP- and DOWN-ARROW keys on thekeyboard cannot be used as they are in a Command Window. Those keys causeyour cursor to travel in the Word screen rather than to scroll through previousinput commands. For navigating in the M-book, you will likely find the scrollbar and the mouse to be more useful than the arrow keys.You may want to run script or function M-files in an M-book. You still musttake care of path business as you do in a Command Window. But assuming youhave done so, M-files are executed in an M-book exactly as in a Command Win-dow. You invoke them simply by typing their name and pressing CTRL+ENTER.The outputs they generate, both intermediate and final, are determined asbefore. In particular, semicolons at ends of lines are important; the commandecho works as before; and so do loops. One thing that does not work so wellis the command more. We have found that, even if more on is executed, helpcommands that run on for more than a page do not come out staggered in anM-book. Thus you may want to bring MATLAB to the foreground and enteryour help requests in the Command Window.Another standard MATLAB feature that does not work so well in M-books isthe...construct for continuing a long command entry on a second line. Wordautomatically converts three dots into a single special ellipsis character andso confuses MATLAB. There are two ways around this difficulty. Either do notuse ellipses (rather simply continue typing and allow Word to wrap as usual —the command will be interpreted properly when passed to MATLAB) or turn offthe "Auto Correct" feature of Word that converts the three dots into an ellipsis.This is most easily done by typing CTRL+Z after the three dots. Alternatively,open Tools : Auto Correct... and change the settings that appear there.One final comment is in order. Another reason to bring MATLAB to theforeground is if you want to use the Current Directory browser, Workspacebrowser, or Editor/Debugger. The relevant icons on the tool bar or buttons onthe menu bar can only be found in the MATLAB Desktop, not in the Wordscreen. However, you can also type pathtool, workspace, or edit directlyinto the M-book, followed by CTRL+ENTER of course.A WarningThe ellipsis difficulty described in the last section is not an isolated difficulty.The various kinds of automatic formatting that Word carries out can trulyconfuse MATLAB. Several such instances that we find particularly annoyingare: fractions (1/2 is converted to a single character 1/2 representing one-half); 100 Chapter 6: M-Booksthe character combination ":)", a construct often used when specifying the rowsof a matrix, which Word converts to a "smiley face" .. ; and various dashes thatwreak havoc with MATLAB's attempts to interpret an ordinary hyphen as aminus sign. Examine these in Tools : Auto Correct... and, if you use M-booksregularly, consider turning them off.A more insidious problem is the following. If you cut and paste characterstrings into an input cell, the characters in the original font may be convertedinto something you don't anticipate in the Courier input cell. Mysterious andunfathomable error messages upon execution are a tip-off to this problem. Ingeneral, you should not copy cells for evaluation unless it is from a cell thathas already been evaluated successfully — it is safer to type in the line anew.Finally, we have seen instances in which a cell, for no discernible reason,fails to evaluate. If this happens, try typing CTRL+ENTER again. If that fails, youmay have to delete and retype the cell. We have also occasionally experiencedthe following problem: Reevaluation of a cell causes its output to appear in anunpredictable place elsewhere in the M-book — sometimes even obliteratingunrelated output in that locale. If that happens, click on the Undo button onthe Word tool bar, retype the input cell before evaluating, and delete the oldinput cell. Chapter 7MATLAB ProgrammingEvery time you create an M-file, you are writing a computer program usingthe MATLAB programming language. You can do quite a lot in MATLABusing no more than the most basic programming techniques that we havealready introduced. In particular, we discussed simple loops (using for) anda rudimentary approach to debugging in Chapter 3. In this chapter, we willcover some further programming commands and techniques that are usefulfor attacking more complicated problems with MATLAB. If you are alreadyfamiliar with another programming language, much of this material will bequite easy for you to pick up! Many MATLAB commands are themselves M-files, which you can examineusing type or edit (for example, enter type isprime to see the M-file forthe command isprime). You can learn a lot about MATLAB programmingtechniques by inspecting the built-in M-files.BranchingFor many user-defined functions, you can use a function M-file that executesthe same sequence of commands for each input. However, one often wants afunction to perform a different sequence of commands in different cases, de-pending on the input. You can accomplish this with a branching command, andas in many other programming languages, branching in MATLAB is usuallydone with the command if, which we will discuss now. Later we will describethe other main branching command, switch.101 102 Chapter 7: MATLAB ProgrammingBranching with ifFor a simple illustration of branching with if, consider the following functionM-file absval.m, which computes the absolute value of a real number:function y = absval(x)if x >= 0y = x;elsey = -x;endThe first line of this M-file states that the function has a single input x anda single output y. If the input x is nonnegative, the if statement is deter-mined by MATLAB to be true. Then the command between the if and theelse statements is executed to set y equal to x, while MATLAB skips thecommand between the else and end statements. However, if x is negative,then MATLAB skips to the else statement and executes the succeeding com-mand, setting y equal to -x. As with a for loop, the indentation of commandsabove is optional; it is helpful to the human reader and is done automaticallyby MATLAB's built-in Editor/Debugger. Most of the examples in this chapter will give peculiar results if their inputis of a different type than intended. The M-file absval.m is designed onlyfor scalar real inputs x, not for complex numbers or vectors. If x is complexfor instance, then x >= 0 checks only if the real part of x is nonnegative,and the output y will be complex in either case. MATLAB has a built-infunction abs that works correctly for vectors of complex numbers.In general, if must be followed on the same line by an expression thatMATLAB will test to be true or false; see the section below on Logical Expres-sions for a discussion of allowable expressions and how they are evaluated.After some intervening commands, there must be (as with for) a correspond-ing end statement. In between, there may be one or more elseif state-ments (see below) and/or an else statement (as above). If the test is true,MATLAB executes all commands between the if statement and the firstelseif, else, or end statement and then skips all other commands un-til after the end statement. If the test is false, MATLAB skips to the firstelseif, else, or end statement and proceeds from there, making a new testin the case of an elseif statement. In the example below, we reformulateabsval.m so that no commands are necessary if the test is false, eliminatingthe need for an else statement. Branching 103function y = absval(x)y = x;if y < 0y = -y;endThe elseif statement is useful if there are more than two alternativesand they can be distinguished by a sequence of true/false tests. It is essen-tially equivalent to an else statement followed immediately by a nested ifstatement. In the example below, we use elseif in an M-file signum.m, whichevaluates the mathematical functionsgn(x) =1 x > 0,0 x = 0,−1 x < 0.(Again, MATLAB has a built-in function sign that performs this function formore general inputs than we consider here.)function y = signum(x)if x > 0y = 1;elseif x == 0y = 0;elsey = -1;endHere if the input x is positive, then the output y is set to 1 and all commandsfrom the elseif statement to the end statement are skipped. (In particular,the test in the elseif statement is not performed.) If x is not positive, thenMATLAB skips to the elseif statement and tests to see if x equals 0. If so, y isset to 0; otherwise y is set to -1. Notice that MATLAB requires a double equalsign == to test for equality; a single equal sign is reserved for the assignmentof values to variables. Like for and the other programming commands you will encounter, if andits associated commands can be used in the Command Window. Doing so canbe useful for practice with these commands, but they are intended mainly foruse in M-files. In our discussion of branching, we consider primarily the caseof function M-files; branching is less often used in script M-files. 104 Chapter 7: MATLAB ProgrammingLogical ExpressionsIn the examples above, we used relational operators such as >=, >, and ==to form a logical expression, and we instructed MATLAB to choose betweendifferent commands according to whether the expression is true or false. Typehelp relop to see all of the available relational operators. Some of theseoperators, such as & (AND) and | (OR), can be used to form logical expressionsthat are more complicated than those that simply compare two numbers. Forexample, the expression (x > 0) | (y > 0) will be true if x or y (or both)is positive, and false if neither is positive. In this particular example, theparentheses are not necessary, but generally compound logical expressionslike this are both easier to read and less prone to errors if parentheses areused to avoid ambiguities.Thus far in our discussion of branching, we have only considered expressionsthat can be evaluated as true or false. While such expressions are sufficientfor many purposes, you can also follow if or elseif with any expressionthat MATLAB can evaluate numerically. In fact, MATLAB makes almost nodistinction between logical expressions and ordinary numerical expressions.Consider what happens if you type a logical expression by itself in the Com-mand Window:>> 2 > 3ans =0When evaluating a logical expression, MATLAB assigns it a value of 0 (forFALSE) or 1 (for TRUE). Thus if you type 2 < 3, the answer is 1. The rela-tional operators are treated by MATLAB like arithmetic operators, inasmuchas their output is numeric. MATLAB makes a subtle distinction between the output of relationaloperators and ordinary numbers. For example, if you type whos after thecommand above, you will see that ans is a logical array. We will give anexample of how this feature can be used shortly. Type help logical formore information.Here is another example:>> 2 | 3ans =1 Branching 105The OR operator | gives the answer 0 if both operands are zero and 1 other-wise. Thus while the output of relational operators is always 0 or 1, anynonzero input to operators such as & (AND), | (OR), and ~ (NOT) is regardedby MATLAB to be true, while only 0 is regarded to be false.If the inputs to a relational operator are vectors or matrices rather thanscalars, then as for arithmetic operations such as + and .*, the operation isdone term-by-term and the output is an array of zeros and ones. Here are someexamples:>> [2 3] < [3 2]ans =1 0>> x = -2:2; x >= 0ans =0 0 1 1 1In the second case, x is compared term-by-term to the scalar 0. Type helprelop or more information.You can use the fact that the output of a relational operator is a logical arrayto select the elements of an array that meet a certain condition. For example,the expression x(x >= 0) yields a vector consisting of only the nonnegativeelements of x (or more precisely, those with nonzero real part). So, if x = -2:2as above,>> x(x >= 0)ans =0 1 2If a logical array is used to choose elements from another array, the two arraysmust have the same size. The elements corresponding to the ones in the logicalarray are selected while the elements corresponding to the zeros are not. Inthe example above, the result is the same as if we had typed x(3:5), but inthis case 3:5 is an ordinary numerical array specifying the numerical indicesof the elements to choose.Next, we discuss how if and elseif decide whether an expression is trueor false. For an expression that evaluates to a scalar real number, the criterionis the same as described above — namely, a nonzero number is treated as truewhile 0 is treated as false. However, for complex numbers only the real partis considered. Thus, in an if or elseif statement, any number with nonzero 106 Chapter 7: MATLAB Programmingreal part is treated as true, while numbers with zero real part are treated asfalse. Furthermore, if the expression evaluates to a vector or matrix, an ifor elseif statement must still result in a single true-or-false decision. Theconvention MATLAB uses is that all elements must be true (i.e., all elementsmust have nonzero real part) for an expression to be treated as true. If anyelement has zero real part, then the expression is treated as false.You can manipulate the way branching is done with vector input by in-verting tests with ~ and using the commands any and all. For example, thestatements if x == 0; ...; end will execute a block of commands (rep-resented here by · · ·) when all the elements of x are zero; if you would liketo execute a block of commands when any of the elements of x is zero youcould use the form if x ~= 0; else; ...; end. Here ~= is the relationaloperator for "does not equal", so the test fails when any element of x is zero,and execution skips past the else statement. You can achieve the same effectin a more straightforward manner using any, which outputs true when anyelement of an array is nonzero: if any(x == 0); ...; end (rememberthat if any element of x is zero, the corresponding element of x == 0 isnonzero). Likewise all outputs true when all elements of an array arenonzero.Here is a series of examples to illustrate some of the features of logicalexpressions and branching that we have just described. Suppose you want tocreate a function M-file that computes the following function:f (x) =sin(x)/x x = 0,1 x = 0.You could construct the M-file as follows:function y = f(x)if x == 0y = 1;elsey = sin(x)/x;endThis will work fine if the input x is a scalar, but not if x is a vector or matrix.Of course you could change / to ./ in the second definition of y, and changethe first definition to make y the same size as x. But if x has both zero andnonzero elements, then MATLAB will declare the if statement to be false anduse the second definition. Then some of the entries in the output array y willbe NaN, "not a number," because 0/0 is an indeterminate form. Branching 107One way to make this M-file work for vectors and matrices is to use a loopto evaluate the function element-by-element, with an if statement inside theloop:function y = f(x)y = ones(size(x));for n = 1:prod(size(x))if x(n) ~= 0y(n) = sin(x(n))/x(n);endendIn the M-file above, we first create the eventual output y as an array of oneswith the same size as the input x. Here we use size(x) to determine thenumber of rows and columns of x; recall that MATLAB treats a scalar or avector as an array with one row and/or one column. Then prod(size(x))yields the number of elements in x. So in the for statement n varies from 1to this number. For each element x(n), we check to see if it is nonzero, andif so we redefine the corresponding element y(n) accordingly. (If x(n) equals0, there is no need to redefine y(n) since we defined it initially to be 1.) We just used an important but subtle feature of MATLAB, namely thateach element of a matrix can be referred to with a single index; for example,if x is a 3 × 2 array then its elements can be enumerated as x(1), x(2), . . . ,x(6). In this way, we avoided using a loop within a loop. Similarly, we coulduse length(x(:)) in place of prod(size(x)) to count the total number ofentries in x. However, one has to be careful. If we had not predefined y to havethe same size as x, but rather used an else statement inside the loop to lety(n) be 1 when x(n) is 0, then y would have ended up a 1 × 6 array ratherthan a 3 × 2 array. We then could have used the command y = reshape(y,size(x)) at the end of the M-file to make y have the same shapeas x. However, even if the shape of the output array is not important, it isgenerally best to predefine an array of the appropriate size before computingit element-by-element in a loop, because the loop will then run faster.Next, consider the following modification of the M-file above:function y = f(x)if x ~= 0y = sin(x)./x;returnend 108 Chapter 7: MATLAB Programmingy = ones(size(x));for n = 1:prod(size(x))if x(n) ~= 0y(n) = sin(x(n))/x(n);endendAbove the loop we added a block of four lines whose purpose is to make theM-file run faster if all the elements of the input x are nonzero. The differencein running time can be significant (more than a factor of 10) if x has a largenumber of elements. Here is how the new block of four lines works. The first ifstatement will be true provided all the elements of x are nonzero. In this case,we define the output y using MATLAB's vector operations, which are generallymuch more efficient than running a loop. Then we use the command returnto stop execution of the M-file without running any further commands. (Theuse of return here is a matter of style; we could instead have indented all ofthe remaining commands and put them between else and end statements.)If, however, x has some zero elements, then the if statement is false and theM-file skips ahead to the commands after the next end statement.Often you can avoid the use of loops and branching commands entirely byusing logical arrays. Here is another function M-file that performs the sametask as in the previous examples; it has the advantage of being more conciseand more efficient to run than the previous M-files, since it avoids a loop inall cases:function y = f(x)y = ones(size(x));n = (x ~= 0);y(n) = sin(x(n))./x(n);Here n is a logical array of the same size as x with a 1 in each place where x hasa nonzero element and zeros elsewhere. Thus the line that defines y(n) onlyredefines the elements of y corresponding to nonzero values of x and leavesthe other elements equal to 1. If you try each of these M-files with an array ofabout 100,000 elements, you will see the advantage of avoiding a loop!Branching with switchThe other main branching command is switch. It allows you to branch amongseveral cases just as easily as between two cases, though the cases must be de-scribed through equalities rather than inequalities. Here is a simple example,which distinguishes between three cases for the input: More about Loops 109function y = count(x)switch xcase 1y = 'one';case 2y = 'two';otherwisey = 'many';endHere the switch statement evaluates the input x and then execution of theM-file skips to whichever case statement has the same value. Thus if theinput x equals 1, then the output y is set to be the string 'one', while if x is2, then y is set to 'two'. In each case, once MATLAB encounters another casestatement or since an otherwise statement, it skips to the end statement,so that at most one case is executed. If no match is found among the casestatements, then MATLAB skips to the (optional) otherwise statement, orelse to the end statement. In the example above, because of the otherwisestatement, the output is 'many' if the input is not 1 or 2.Unlike if, the command switch does not allow vector expressions, but itdoes allow strings. Type help switch to see an example using strings. Thisfeature can be useful if you want to design a function M-file that uses a stringinput argument to select among several different variants of a program youwrite. Though strings cannot be compared with relational operators such as ==(unless they happen to have the same length), you can compare strings in anif or elseif statement by using the command strcmp. Type help strcmpto see how this command works; for an example of its use in conjunctionwith if and elseif, enter type hold.More about LoopsIn Chapter 3 we introduced the command for, which begins a loop — asequence of commands to be executed multiple times. When you use for,you effectively specify the number of times to run the loop in advance (thoughthis number may depend for instance on the input to a function M-file). Some-times you may want to keep running the commands in a loop until a certaincondition is met, without deciding in advance on the number of iterations. InMATLAB, the command that allows you to do so is while. 110 Chapter 7: MATLAB Programming➱ Using while, one can easily end up accidentally creating an "infiniteloop", one that will keep running indefinitely because the conditionyou set is never met. Remember that you can generally interruptthe execution of such a loop by typing CTRL+C; otherwise, you mayhave to shut down MATLAB.Open-Ended LoopsHere is a simple example of a script M-file that uses while to numericallysum the infinite series 1/14+ 1/24+ 1/34+ · · ·, stopping only when the termsbecome so small (compared to the machine precision) that the numerical sumstops changing:n = 1;oldsum = -1;newsum = 0;while newsum > oldsumoldsum = newsum;newsum = newsum + nˆ(-4);n = n + 1;endnewsumHere we initialize newsum to 0 and n to 1, and in the loop we successivelyadd nˆ(-4) to newsum, add 1 to n, and repeat. The purpose of the variableoldsum is to keep track of how much newsum changes from one iterationto the next. Each time MATLAB reaches the end of the loop, it starts overagain at the while statement. If newsum exceeds oldsum, the expression inthe while statement is true, and the loop is executed again. But the firsttime the expression is false, which will happen when newsum and oldsum areequal, MATLAB skips to the end statement and executes the next line, whichdisplays the final value of newsum (the result is 1.0823 to five significantdigits). The initial value of -1 that we gave to oldsum is somewhat arbitrary,but it must be negative so that the first time the while statement is executed,the expression therein is true; if we set oldsum to 0 initially, then MATLABwould skip to the end statement without ever running the commands in theloop. Even though you can construct an M-file like the one above without decidingexactly how many times to run the loop, it may be useful to consider roughlyhow many times it will need to run. Since the floating point computations on More about Loops 111most computers are accurate to about 16 decimal digits, the loop aboveshould run until nˆ(-4) is about 10ˆ(-16), that is, until n is about 10ˆ4.Thus the computation will take very little time on most computers. However,if the exponent were 2 and not 4, the computation would take about 10ˆ8operations, which would take a long time on most (current) computers —long enough to make it wiser for you to find a more efficient way to sum theseries, for example using symsum if you have the Symbolic Math Toolbox! Though we have classified it here as a looping command, while also hasfeatures of a branching command. Indeed, the types of expressions allowedand the method of evaluation for a while statement are exactly the same asfor an if statement. See the section Logical Expressions above for adiscussion of the possible expressions you can put in a while statement.Breaking from a LoopSometimes you may want MATLAB to jump out of a for loop prematurely,for example if a certain condition is met. Or, in a while loop, there may be anauxiliary condition that you want to check in addition to the main conditionin the while statement. Inside either type of loop, you can use the commandbreak to tell MATLAB to stop running the loop and skip to the next line afterthe end of the loop. The command break is generally used in conjunction withan if statement. The following script M-file computes the same sum as in theprevious example, except that it places an explicit upper limit on the numberof iterations:newsum = 0;for n = 1:100000oldsum = newsum;newsum = newsum + nˆ(-4);if newsum == oldsumbreakendend newsumIn this example, the loop stops after n reaches 100000 or when the variablenewsum stops changing, whichever comes first. Notice that break ignoresthe end statement associated with if and skips ahead past the nearest endstatement associated with a loop command, in this case for. 112 Chapter 7: MATLAB ProgrammingOther Programming CommandsIn this section we describe several more advanced programming commandsand techniques.SubfunctionsIn addition to appearing on the first line of a function M-file, the commandfunction can be used later in the M-file to define an auxiliary function, orsubfunction, which can be used anywhere within the M-file but will not beaccessible directly from the command line. For example, the following M-filesums the cube roots of a vector x of real numbers:function y = sumcuberoots(x)y = sum(cuberoot(x));% ---- Subfunction starts here.function z = cuberoot(x)z = sign(x).*abs(x).ˆ(1/3);Here the subfunction cuberoot takes the cube root of x element-by-element,but it cannot be used from the command line unless placed in a separate M-file.You can only use subfunctions in a function M-file, not in a script M-file. Forexamples of the use of subfunctions, you can examine many of MATLAB's built-in function M-files. For example, type ezplot will display three differentsubfunctions.Commands for Parsing Input and OutputYou may have noticed that many MATLAB functions allow you to vary thetype and/or the number of arguments you give as input to the function. Youcan use the commands nargin, nargout, varargin, and varargout in yourown M-files to handle variable numbers of input and/or output arguments,whereas to treat different types of input arguments differently you can usecommands such as isnumeric and ischar.When a function M-file is executed, the functions nargin and nargout re-port respectively the number of input and output arguments that were speci-fied on the command line. To illustrate the use of nargin, consider the follow-ing M-file add.m that adds either 2 or 3 inputs:function s = add(x, y, z)if nargin < 2 Other Programming Commands 113error('At least two input arguments are required.')endif nargin == 2s = x + y;elses = x + y + z;endFirst the M-file checks to see if fewer than 2 input arguments were given, andif so it prints an error message and quits. (See the next section for more abouterror and related commands.) Since MATLAB automatically checks to see ifthere are more arguments than specified on the first line of the M-file, there isno need to do so within the M-file. If the M-file reaches the second if statementin the M-file above, we know there are either 2 or 3 input arguments; the ifstatement selects the proper course of action in either case. If you type, forinstance, add(4,5) at the command line, then within the M-file, x is set to4, y is set to 5, and z is left undefined; thus it is important to use nargin toavoid referring to z in cases where it is undefined.To allow a greater number of possible inputs to add.m, we could add ad-ditional arguments on the first line of the M-file and add more cases fornargin. A better way to do this is to use the specially named input argumentvarargin:function s = add(varargin)s = sum([varargin{:}]);In this example, all of the input arguments are assigned to the cell arrayvarargin. The expression varargin{:} returns a comma-separated list ofthe input arguments. In the example above, we convert this list to a vector byenclosing it in square brackets, forming suitable input for sum.The sample M-files above assume their input arguments are numeric andwill attempt to add them even if they are not. This may be desirable in somecases; for instance, both M-files above will correctly add a mixture of numericand symbolic inputs. However, if some of the input arguments are strings,the result will be either an essentially meaningless numerical answer or anerror message that may be difficult to decipher. MATLAB has a number oftest functions that you can use to make an M-file treat different types of inputarguments differently — either to perform different calculations or to producea helpful error message if an input is of an unexpected type. For a list ofsome of these test functions, look up the commands beginning with is in theProgramming Commands section of the Glossary. 114 Chapter 7: MATLAB ProgrammingAs an example, here we use isnumeric in the M-file add.m to print anerror message if any of the inputs are not numeric:function s = add(varargin)if ~isnumeric([varargin{:}])error('Inputs must be floating point numbers.')ends = sum([varargin{:}]);When a function M-file allows multiple output arguments, then if fewer out-put arguments are specified when the function is called, the remaining outputsare simply not assigned. Recall that if no output arguments are explicitly spec-ified on the command line, then a single output is returned and assigned tothe variable ans. For example, consider the following M-file rectangular.mthat changes coordinates from polar to rectangular:function [x, y] = rectangular(r, theta)x = r.*cos(theta);y = r.*sin(theta);If you type rectangular(2, 1) at the command line, then the answer willbe just the x coordinate of the point with polar coordinates (2, 1). The followingmodification to rectangular.m adjusts the output in this case to be a complexnumber x + iy containing both coordinates:function [x, y] = rectangular(r, theta)x = r.*cos(theta);y = r.*sin(theta);if nargout < 2x = x + i*y;endSee the online help for varargout and the functions described above for ad-ditional information and examples.User Input and Screen OutputIn the previous section we used error to print a message to the screen andthen terminate execution of an M-file. You can also print messages to thescreen without stopping execution of the M-file with disp or warning. Notsurprisingly, warning is intended to be used for warning messages, whenthe M-file detects a problem that might affect the validity of its result but isnot necessarily serious. You can suppress warning messages, either from the Other Programming Commands 115command prompt or within an M-file, with the command warning off. Thereare several other options for how MATLAB should handle warning messages;type help warning for details.In Chapter 4 we used disp to display the output of a command withoutprinting the "ans =" line. You can also use disp to display informationalmessages on the screen while an M-file is running, or to combine numericaloutput with a message on the same line. For example, the commandsx = 2 + 2; disp(['The answer is ' num2str(x) '.'])will set x equal to 4 and then print The answer is 4.MATLAB also has several commands to solicit input from the user run-ning an M-file. At the end of Chapter 3 we discussed three of them: pause,keyboard, and input. Briefly, pause simply pauses execution of an M-fileuntil the user hits a key, while keyboard both pauses and gives the user aprompt to use like the regular command line. Typing return continues ex-ecuting the M-file. Lastly, input displays a message and allows the user toenter input for the program on a single line. For example, in a program thatmakes successive approximations to an answer until some accuracy goal ismet, you could add the following lines to be executed after a large number ofsteps have been taken:answer = input(['Algorithm is converging slowly; ', ...'continue (yes/no)? '], 's');if ~isequal(answer, 'yes')returnendHere the second argument 's' to input directs MATLAB not to evaluatethe answer typed by the user, just to assign it as a character string to thevariable answer. We use isequal to compare the answer to the string 'yes'because == can only be used to compare arrays (in this case strings) of thesame length. In this case we decided that if the user types anything but thefull word yes, the M-file should terminate. Other approaches would be toonly compare the first letter answer(1) to 'y', to stop only if the answer is'no', etc.If a figure window is open, you can use ginput to get the coordinates of apoint that the user selects with the mouse. As an example, the following M-fileprints an "X" where the user clicks:function xmarksthespotif isempty(get(0, 'CurrentFigure')) 116 Chapter 7: MATLAB Programmingerror('No current figure.')endflag = ~ishold;if flaghold onenddisp('Click on the point where you want to plot an X.')[x, y] = ginput(1);plot(x, y, 'xk')if flaghold offendFirst the M-file checks to see if there is a current figure window. If so, itproceeds to set the variable flag to 1 if hold off is in effect and 0 if holdon is in effect. The reason for this is that we need hold on in effect to plotan "X" without erasing the figure, but afterward we want to restore the figurewindow to whichever state it was in before the M-file was executed. The M-filethen displays a message telling the user what to do, gets the coordinates of thepoint selected with ginput(1), and plots a black "X" at those coordinates.The argument 1 to ginput means to get the coordinates of a single point;using ginput with no input argument would collect coordinates of severalpoints, stopping only when the user presses the ENTER key.In the next chapter we describe how to create a GUI (Graphical User Inter-face) within MATLAB to allow more sophisticated user interaction.EvaluationThe commands eval and feval allow you to run a command that is storedin a string as if you had typed the string on the command line. If the entirecommand you want to run is contained in a string str, then you can exe-cute it with eval(str). For example, typing eval('cos(1)') will producethe same result as typing cos(1). Generally eval is used in an M-file thatuses variables to form a string containing a command; see the online help forexamples.You can use feval on a function handle or on a string containing the nameof a function you want to execute. For example, typing feval('atan2', 1,0) or feval(@atan2, 1, 0) is equivalent to typing atan2(1, 0). Oftenfeval is used to allow the user of an M-file to input the name of a functionto use in a computation. The following M-file iterate.m takes the name of a Other Programming Commands 117function and an initial value and iterates the function a specified number oftimes:function final = iterate(func, init, num)final = init;for k = 1:numfinal = feval(func, final);endTyping iterate('cos', 1, 2) yields the numerical value of cos(cos(1)),while iterate('cos', 1, 100) yields an approximation to the real num-ber x for which cos(x) = x. (Think about it!) Most MATLAB commands thattake a function name argument use feval, and as with all these commands,if you give the name of an inline function to feval, you should not enclose itin quotes.DebuggingIn Chapter 3 we discussed some rudimentary debugging procedures. Onesuggestion was to insert the command keyboard into an M-file, for instanceright before the line where an error occurs, so that you can examine theWorkspace of the M-file at that point in its execution. A more effective and flex-ible way to do this kind of debugging is to use dbstop and related commands.With dbstop you can set a breakpoint in an M-file in a number of ways, forexample, at a specific line number, or whenever an error occurs. Type helpdbstop for a list of available options.When a breakpoint is reached, a prompt beginning with the letter K willappear in the Command Window, just as if keyboard were inserted in theM-file at the breakpoint. In addition, the location of the breakpoint is high-lighted with an arrow in the Editor/Debugger (which is opened automaticallyif you were not already editing the M-file). At this point you can examine inthe Command Window the variables used in the M-file, set another breakpointwith dbstop, clear breakpoints with dbclear, etc. If you are ready to continuerunning the M-file, type dbcont to continue or dbstep to step through the fileline-by-line. You can also stop execution of the M-file and return immediatelyto the usual command prompt with dbquit. You can also perform all the command-line functions that we describedin this section with the mouse and/or keyboard shortcuts in theEditor/Debugger. See the section Debugging Techniques in Chapter 11 formore about debugging commands and features of the Editor/Debugger. 118 Chapter 7: MATLAB ProgrammingInteracting with the Operating System This section is somewhat advanced, as is the following chapter. On a firstreading, you might want to skip ahead to Chapter 9.Calling External ProgramsMATLAB allows you to run other programs on your computer from its com-mand line. If you want to enter UNIX or DOS file manipulation commands,you can use this feature as a convenience to avoid opening a separate window.Or you may want to use MATLAB to graph the output of a program writ-ten in a language such as FORTRAN or C. For large-scale computations, youmay wish to combine routines written in another programming language withroutines you write in MATLAB.The simplest way to run an external program is to type an exclamation pointat the beginning of a line, followed by the operating system command you wantto run. For example, typing !dir on a Windows system or !ls -l on a UNIXsystem will generate a more detailed listing of the files in the current workingdirectory than the MATLAB command dir. In Chapter 3 we described dir andother MATLAB commands, such as cd, delete, pwd, and type, that mimicsimilar commands from the operating system. However, for certain operations(such as renaming a file) you may need to run an appropriate command fromthe operating system. If you use the operating system interface in an M-file that you want to runon either a Windows or UNIX system, you should use the test functionsispc and/or isunix to set off the appropriate commands for each type ofsystem, for example, if isunix; ...; else; ...; end. If you need todistinguish between different versions of UNIX (Linux, Solaris, etc.), you canuse computer instead of isunix.The output from an operating system command preceded by ! can only bedisplayed to the screen. To assign the output of an operating system com-mand to a variable, you must use dos or unix. Though each is only docu-mented to work for its respective operating system, in current versions of MAT-LAB they work interchangeably. For example, if you type [stat, data]=dos('myprog 0.5 1000'), the program myprog will be run with commandline arguments 0.5 and 1000 and its "standard output" (which would nor-mally appear on the screen) will be saved as a string in the variable data. (Thevariable stat will contain the exit status of the program you run, normally 0 Interacting with the Operating System 119if the program runs without error.) If the output of your program consists onlyof numbers, then str2num(data) will yield a row vector containing thosenumbers. You can also use sscanf to extract numbers from the string data;type help sscanf for details.➱ A program you run with !, dos, or unix must be in the currentdirectory or elsewhere in the path your system searches forexecutable files; the MATLAB path will not be searched.If you are creating a program that will require extensive communicationbetween MATLAB and an external FORTRAN or C program, then compilingthe external program as a MEX file will be more efficient than using dos orunix. To do so, you must write some special instructions into the externalprogram and compile the program from within MATLAB using the commandmex. This will result in a file with the extension .mex that you can run fromwithin MATLAB just as you would run an M-file. The advantage is that acompiled program will generally run much faster than an M-file, especiallywhen loops are involved.The instructions you need to write into your program to compile it with mexare described in MATLAB : Using MATLAB : External Interfaces/API inthe Help Browser and in the "MEX, API, & Compilers" section of the web site for the page entitled "Is there a tutorial for creating MEX-files withemphasis on C MEX-files?" The instructions depend to some extent on whetheryour program is written in FORTRAN or C, but they are not hard to learn ifyou already know one of these languages. MATLAB version 6 also provides theMATLAB Java Interface, which enables you to create and access Java objectsfrom within MATLAB.File Input and OutputIn Chapter 3 we discussed how to use save and load to transfer variablesbetween the Workspace and a disk file. By default the variables are written andread in MATLAB's own binary format, which is signified by the file extension.mat. You can also read and write text files, which can be useful for sharingdata with other programs. With save you type -ascii at the end of the lineto save numbers as text rounded to 8 digits, or -ascii -double for 16-digitaccuracy. With load the data are assumed to be in text format if the file namedoes not end in .mat. This provides an alternative to importing data with dos 120 Chapter 7: MATLAB Programmingor unix in case you have previously run an external program and saved theresults in a file. MATLAB 6 also offers an interactive tool called the Import Wizard to readdata from files (or the system clipboard) in different formats; to start it typeuiimport (optionally followed by a file name) or select File : ImportData....For more control over file input and output — for example to annotatenumeric output with text — you can use fopen, fprintf, and related com-mands. MATLAB also has commands to read and write graphics and soundfiles. Type help iofun for an overview of input and output functions. Chapter 8SIMULINK and GUIsIn this chapter we describe SIMULINK, a MATLAB accessory for simulat-ing dynamical processes, and GUIDE, a built-in tool for creating your owngraphical user interfaces. These brief introductions are not comprehensive,but together with the online documentation they should be enough to get youstarted.SIMULINKIf you want to learn about SIMULINK in depth, you can read the massive PDFdocument SIMULINK: Dynamic System Simulation for MATLAB that comeswith the software. Here we give a brief introduction for the casual user whowants to get going with SIMULINK quickly. You start SIMULINK by double-clicking on SIMULINK in the Launch Pad, by clicking on the SIMULINKbutton on the MATLAB Desktop tool bar, or simply by typing simulink inthe Command Window. This opens the SIMULINK library window, which isshown for UNIX systems in Figure 8-1. On Windows systems, you see insteadthe SIMULINK Library Browser, shown in Figure 8-2.To begin to use SIMULINK, click New : Model from the File menu. Thisopens a blank model window. You create a SIMULINK model by copying units,called blocks, from the various SIMULINK libraries into the model window.We will explain how to use this procedure to model the homogeneous linearordinary differential equation u + 2u + 5u = 0, which represents a dampedharmonic oscillator.First we have to figure out how to represent the equation in a way thatSIMULINK can understand. One way to do this is as follows. Since the timevariable is continuous, we start by opening the "Continuous" library, in UNIX121 SIMULINK 123Figure 8-3: The Continuous Library.by double-clicking on the third icon from the left in Figure 8-1, or in Windowseither by clicking on the to the left of the "Continuous" icon at the topright of Figure 8-2, or else by clicking on the small icon to the left of theword "Continuous" in the left panel of the SIMULINK Library Browser. Whenopened, the "Continuous" library looks like Figure 8-3.Notice that uand u are obtained from u and u (respectively) by integrating.Therefore, drag two copies of the Integrator block into the model window, andline them up with the mouse. Relabel them (by positioning the mouse at theend of the text under the block, hitting the BACKSPACE key a few times to erasewhat you don't want, and typing something new in its place) to read u and u.Note that each Integrator block has an input port and an output port. Alignthe output port of the u Integrator with the input port of the u Integratorand join them with an arrow, using the left button on the mouse. Your modelwindow should now look like this:1su'1suThis models the fact that u is obtained by integration from u . Now thedifferential equation can be rewritten u = −(5u + 2u ), and u is obtainedby integration from u . So we want to add other blocks to implement theserelationships. For this purpose we add three Gain blocks, which implement 124 Chapter 8: SIMULINK and GUIsmultiplication by a constant, and one Sum block, used for addition. Theseare all chosen from the "Math" library (fourth from the right in Figure 8-1, orfourth from the top in Figure 8-2). Hooking them up the same way we did withthe Integrator blocks gives a model window that looks something like this:1su'1su1Gain21Gain11GainWe need to go back and edit the properties of the Gain blocks, to changethe constants by which they multiply from the default of 1 to 5 (in "Gain"),−1 (in "Gain1"), and 2 (in "Gain2"). To do this, double-click on each Gainblock in turn. A Block Parameters box will open in which you can change theGain parameter to whatever you need. Next, we need to send u , the outputof the first Integrator block, to the input port of block "Gain2". This presentsa problem, since an Integrator block only has one output port and it's alreadyconnected to the next Integrator block. So we need to introduce a branch line.Position the mouse in the middle of the arrow connecting the two Integrators,hold down the CTRL key with one hand, simultaneously push down the leftmouse button with the other hand, and drag the mouse around to the inputport of the block entitled "Gain2". At this point we're almost done; we justneed a block for viewing the output. Open up the "Sinks" library and drag acopy of the Scope block into the model window. Hook this up with a branchline (again using the CTRL key) to the line connecting the second Integratorand the Gain block. At this point you might want to relabel some more of theblocks (by editing the text under each block), and also label some of the arrows(by double-clicking on the arrow shaft to open a little box in which you cantype a label). We end up with the model shown in Figure 8-4.Now we're ready to run our simulation. First, it might be a good idea to savethe model, using Save as... from the File menu. One might choose to give itthe name li e OD . (MATLAB automatically adds the file extension . l.)To see what is happening during the simulation, double-click on the Scopeblock to open an "oscilloscope" that will plot u as a function of t. Of courseone needs to set initial conditions also; this can be done by double-clicking on SIMULINK 125Figure 8-4: A Finished SIMULINK Model.the Integrator blocks and changing the line of the Block Parameters box thatreads "Initial condition". For example, suppose we set the initial condition foru (in the first Integrator block) to 5 and the condition for u (in the secondIntegrator block) to 1. In other words, we are solving the systemu + 2u + 5u = 0,u(0) = 1,u (0) = 5,which happens to have the exact solutionu(t) = 3e−tsin(2t) + e−tcos(2t). Your first instinct might be to rely on the Derivative block, rather than theIntegrator block, in simulating differential equations. But this has twodrawbacks: It is harder to put in the initial conditions, and also numericaldifferentiation is much less stable than numerical integration.Now go to the Simulation menu and hit Start. You should see in the Scopewindow something like Figure 8-5. This of course is simply the graph of thefunction 3e−tsin(2t) + e−tcos(2t). (By the way, you might need to change thescale on the vertical axis of the Scope window. Clicking on the "binoculars" icondoes an "automatic" rescale, and right-clicking on the vertical axis opens anAxes Properties... menu that enables you to manually select the minimumand maximum values of the dependent variable.) It is easy to go back andchange some of the parameters and rerun the simulation again.Finally, suppose one now wants to study the inhomogeneous equation for"forced oscillations," u + 2u + 5u = g(t), where g is a specified "forcing" term. 126 Chapter 8: SIMULINK and GUIsFigure 8-5: Scope Output.For this, all we have to do is add another block to the model from the "Sources"library. Click on the shaft of the arrow at the top of the model going into thefirst Integrator and use Cut from the Edit menu to remove it. Then drag inanother "Sum" block before the first Integrator and input a suitable source toone input port of the "Sum" block. For example, if g(t) is to represent "noise,"drag the Band-Limited White Noise block from the "Sources" library into themodel and hook everything up as shown in Figure 8-6.The output from this revised model (with the default values of 0.1 for thenoise power and 0.1 for the noise sample time) looks like Figure 8-7. The effectof noise on the system is clearly visible from the simulation.Figure 8-6: Model for the Inhomogeneous Equation. Graphical User Interfaces (GUIs) 127Figure 8-7: Scope Output for the InhomogeneousEquation.Graphical User Interfaces (GUIs)With MATLAB you can create your own Graphical User Interface, or GUI,which consists of a Figure window containing menus, buttons, text, graphics,etc., that a user can manipulate interactively with the mouse and keyboard.There are two main steps in creating a GUI: One is designing its layout, andthe other is writing callback functions that perform the desired operationswhen the user selects different features.GUI Layout and GUIDESpecifying the location and properties of different objects in a GUI can be donewith commands such as uicontrol, uimenu, and uicontextmenu in an M-file. MATLAB also provides an interactive tool (a GUI itself !) called GUIDEthat greatly simplifies the task of building a GUI. We will describe here howto get started writing GUIs with the MATLAB 6 version of GUIDE, which hasbeen significantly enhanced over previous versions. One possible drawback of GUIDE is that it equips your GUI with commandsthat are new in MATLAB 6 and it saves the layout of the GUI in a binary. i file. If your goal is to create a robust GUI that many different users can 128 Chapter 8: SIMULINK and GUIsuse with different versions of MATLAB, you may still be better off writingthe GUI from scratch as an M-file.To open GUIDE, select File:New:GUI from the Desktop menu bar or typeguide in the Command Window. If this is the first time you have run GUIDE,you will next see a window that encourages you to click on "View GUIDEApplication Options dialog". We recommend that you do so to see what youroptions are, but leave the settings as is for now. After you click "OK", theLayout Editor will appear, containing a large white area with a grid. As withmost MATLAB windows, the Layout Editor has a tool bar with shortcuts tomany of the menu functions we describe below.You can start building a GUI by clicking on one of the buttons to the left ofthe grid, then moving to a desired location in the grid, and clicking again toplace an object on the grid. To see what type of object each button correspondsto, move the mouse over the button but don't click; soon a yellow box withthe name of the button will appear. Once you have placed an object on thegrid, you can click and drag (hold down the left mouse button and move themouse) on the middle of the object to move it or click and drag on a corner toresize the object. After you have placed several objects, you can select multipleobjects by clicking and dragging on the background grid to enclose them witha rectangle. Then you can move the objects as a block with the mouse, or alignthem by selecting Align Objects from the Layout menu.To change properties of an object such as its color, the text within it, etc.,you must open the Property Inspector window. To do so, you can double-clickon an object, or choose Property Inspector from the Tools menu and thenselect the object you want to alter with the left mouse button. You can leavethe Property Inspector open throughout your GUIDE session and go backand forth between it and the Layout Editor. Let's consider an example thatillustrates several of the more important properties.Figure 8-8 shows an example of what the Layout Editor window looks likeafter several objects have been placed and their properties adjusted. Thepurpose of this sample GUI is to allow the user to type a MATLAB plot-ting command, see the result appear in the same window, and modify thegraph in a few ways. Let us describe how we created the objects that make upthe GUI.The boxes on the top row, as well as the one labeled "Set axis scaling:", areStatic Text boxes, which the user of the GUI will not be allowed to manipulate.To create each of them, we first clicked on the "Static Text" button — theone to the right of the grid labeled "TXT" — and then clicked in the grid wherewe wanted to add the text. Next, to set the text for the box we opened the Graphical User Interfaces (GUIs) 129Figure 8-8: The Layout Editor Window.Property Inspector and clicked on the square button next to "String", whichopens a new window in which to change the default text. Finally, we resizedeach box according to the length of its text.The buttons labeled "Plot it!", "Change axis limits", and "Clear Figure" areall Push Button objects, created using the button to the left of the grid labeled"OK". To make these buttons all the same size, we first created one of themand then after sizing it, we duplicated it (twice) by clicking the right mousebutton on the existing object and selecting Duplicate. We then moved eachnew Push Button to a different position and changed its text in the same wayas we did for the Static Text boxes.The blank box near the top of the grid is an Edit Text box, which allows theuser to enter text. We created it with the button to the left of the grid labeled"EDIT" and then cleared its default text in the same way that we changed textbefore. Below the Edit Text box is a large Axes box, created with the buttoncontaining a small graph, and in the lower right the button labeled "Hold isOFF" is a Toggle Button, created with the button labeled "TGL". For toggling 130 Chapter 8: SIMULINK and GUIs(on–off) commands you could also use a Radio Button or a Checkbox, denotedrespectively by the buttons with a dot and a check mark in them. Finally, thebox on the right that says "equal" is a Popup Menu — we'll let you find itsbutton in the Layout Editor since it is hard to describe! Popup Menus andListbox objects allow you to let the user choose among several options.We moved, resized, and in most cases changed the properties of each objectsimilarly to the way we described above. In the case of the Popup Menu, afterwe selected the "String" button in the Property Inspector, we entered into thewindow that appeared three words on three separate lines: equal, normal,and square. Using multiple lines is necessary to give the user multiple choicesin a Popup Menu or Listbox object. In addition to populating your GUI with the objects we described above, youcan create a menu bar for it using the Menu Editor, which you can open byselecting Edit Menubar from the Layout menu. You can also use the MenuEditor to create a context menu for an object; this is a menu that appearswhen you click the right mouse button on the object. See the onlinedocumentation for GUIDE to learn how to use the Menu Editor.We also gave our GUI a title, which will appear in the titlebar of its window,as follows. We clicked on the grid in the Layout Editor to select the entire GUI(as opposed to an object within it) and went to the Property Inspector. Therewe changed the text to the right of "Name" from "Untitled" to "Simple PlotGUI".Saving and Running a GUITo save a GUI, select Save As... from the File menu. Type a file name for yourGUI without any extension; for the GUI described above we chose lo i.Saving creates two files, an M-file and a binary file with extension . i , soin our case the resulting files were named lo i. and lo i. i .When you save a GUI for the first time, the M-file for the GUI will appear ina separate Editor/Debugger window. We will describe how and why to modifythis M-file in the next section.➱ The instructions in this and the following section assume the defaultsettings of the Application Options, which you may have inspectedupon starting GUIDE, as described above. Otherwise, you can accessthem from the Tools menu. We assume in particular that "Generate.fig file and .m file", "Generate callback function prototypes", and"Application allows only one instance to run" are selected. Graphical User Interfaces (GUIs) 131Figure 8-9: A Simple GUI.Once saved, you can run the GUI from the Command Window by typing itsname, in our case plotgui, whether or not GUIDE is running. Both the . ifile and the . file must be in your current directory or MATLAB path. Youcan also run it from the Layout Editor by typing CTRL+T or selecting ActivateFigure from the Tools menu. A copy of the GUI will appear in a separatewindow, without all the surrounding menus and buttons of the Layout Editor.(If you have added new objects since the last time you saved or activatedthe GUI, the M-file associated to the GUI will also be brought to the front.)Figure 8-9 shows how the GUI we created above looks when activated.Notice that the appearance of the GUI is slightly different than in theGUIDE window; in particular, the font size may differ. For this reason youmay have to go back to the GUIDE window after activating a GUI and resizesome objects accordingly. The changes you make will not immediately appearin the active GUI; to see their effect you must activate the GUI again.The objects you create in the Layout Editor are inert within that window —you can't type text in the Edit Text box, you can't see the additional options byclicking on the Popup Menu, etc. But in an activated GUI window, objects suchas Toggle Buttons and Popup Menus will respond to mouse clicks. However,they will not actually perform any functions until you write a callback functionfor each of them. 132 Chapter 8: SIMULINK and GUIsGUI Callback FunctionsWhen you are ready to create a callback function for a given object, clickthe right mouse button on the object and select Edit Callback. The M-fileassociated with the GUI will be brought to the front in an Editor/Debuggerwindow, with the cursor in a block of lines like the ones below. (If you haven'tyet saved the GUI, you will be prompted to do so first, so that GUIDE knowswhat name to give the M-file.)function varargout = pushbutton1 Callback(h, eventdata, handles, varargin)% Stub for Callback of the uicontrol handles.pushbutton1.disp('pushbutton1 Callback not implemented yet.')% ------------------- end pushbutton1 Callback -----------------------In this case we have assumed that the object you selected was the first PushButton that you created in the Layout Editor; the string "pushbutton1" aboveis its default tag. (Another way to find the tag for a given object is to selectit and look next to "Tag" in the Property Inspector.) All you need to do nowto bring this Push Button to life is to replace the disp command line in thetemplate shown above with the commands that you want performed when theuser clicks on the button. Of course you also need to save the M-file, which youcan do in the usual way from the Editor/Debugger, or by activating the GUIfrom the Layout Editor. Each time you save or activate a GUI, a block of fourlines like the ones above is automatically added to the GUI's M-file for anynew objects or menu items that you have added to the GUI and that shouldhave callback functions.In the example plotgui from the previous section, there is one case wherewe used an existing MATLAB command as a callback function. For the PushButton labeled "Change axis limits", we simply entered axlimdlg into itscallback function in lo i. . This command opens a dialog box that allowsa user to type new values for the ranges of the x and y axes. MATLAB has anumber of dialog boxes that you can use either as callback functions or in anordinary M-file. For example, you can use inputdlg in place of input. Typehelp uitools for information on the available dialog boxes.For the Popup Menu on the right side of the GUI, we put the following linesinto its callback function template:switch get(h, 'Value')case 1axis equalcase 2axis normal Graphical User Interfaces (GUIs) 133case 3axis squareendEach time the user of the GUI selects an item from a Popup Menu, MATLABsets the "Value" property of the object to the line number selected and runsthe associated callback function. As we described in Chapter 5, you can useget to retrieve the current setting of a property of a graphics object. Whenyou use the callback templates provided by GUIDE as we have described,the variable h will contain the handle (the required first argument of getand set) for the associated object. (If you are using another method to writecallback functions, you can use the MATLAB command gcbo in place ofh.) For our sample GUI, line 1 of the Popup Menu says "equal", and if theuser selects line 1, the callback function above runs axis equal; line 2 says"normal"; etc. You may have noticed that in Figure 8-9 the Popup Menu says "normal"rather than "equal" as in Figure 8-8; that's because we set its "Value"property to 2 when we created the GUI, using the Property Inspector. In thisway you can make the default selection something other than the first itemin a Popup Menu or Listbox.For the Push Button labeled "Plot it!", we wrote the following callbackfunction:set(handles.figure1, 'HandleVisibility', 'callback')eval(get(handles.edit1, 'String'))Here handles.figure1 and handles.edit1 are the handles for the en-tire GUI window and for the Edit Text box, respectively. Again these vari-ables are provided by the callback templates in GUIDE, and if you do notuse this feature you can generate the appropriate handles with gcbf andfindobj(gcbf, 'Tag', 'edit1'), respectively. The second line of the call-back function above uses get to find the text in the Edit Text box and thenruns the corresponding command with eval. The first line uses set to makethe GUI window accessible to graphics commands used within callback func-tions; if we did not do this, a plotting command run by the second line wouldopen a separate figure window. Another way to enable plotting within a GUI window is to selectApplication Options from the Tools menu in the Layout Editor, andwithin the window that appears change "Command-line accessibility" to"On". This has the possible drawback of allowing plotting commands the 134 Chapter 8: SIMULINK and GUIsuser types in the Command Window to affect the GUI window. A saferapproach is to set "Command-line accessibility" to "User-specified", click onthe grid in the Layout Editor to select the entire GUI, go to the PropertyInspector, and change "HandleVisibility" to "callback". This would eliminatethe need to select this property with set in each of the callback functionsabove and below that run graphics commands.Here is our callback function for the Push Button labeled "Clear figure":set(handles.edit1, 'String', '')set(handles.figure1, 'HandleVisibility', 'callback')cla resetThe first line clears the text in the Edit Text box and the last line clears theAxes box in the GUI window. (If your GUI contains more than one Axes box,you can use axes to select the one you want to manipulate in each of yourcallback functions.)We used the following callback function for the Toggle Button labeled "Holdis OFF":set(handles.figure1, 'HandleVisibility', 'callback')if get(h, 'Value')hold onset(h, 'String', 'Hold is ON');elsehold offset(h, 'String', 'Hold is OFF');endWe get the "Value" property of the Toggle Button in the same way as in thethe Popup Menu callback function above, but for a Toggle Button this valueis either 0 if the button is "out" (the default) or 1 if the button is pressed "in".(Radio Buttons and Checkboxes also have a "Value" property of either 0 or 1.)When the user first presses the Toggle Button, the callback function aboveruns hold on and resets the string displayed on the Toggle Button to reflectthe change. The next time the user presses the button, these operations arereversed. We can also associate a callback function with the Edit Text box; thisfunction will be run each time the user presses the ENTER key after typingtext in the box. The callback function eval(get(h, 'String')) will runthe command just typed, providing an alternative to (or making superfluous)the "Plot it!" button. Graphical User Interfaces (GUIs) 135Finally, if you create a GUI with an Axes box like we did, you may notice thatGUIDE puts in the GUI's M-file a template like a callback template but labeled"ButtondownFcn" instead. When the user clicks in an Axes object, this typeof function is called rather than a callback function, but within the templateyou can write the function just as you would write a callback function. Youcan also associate such a function with an object that already has a callbackfunction by clicking the right mouse button on the object in the Layout Editorand selecting Edit ButtondownFcn. This function will be run when theuser clicks the right mouse button (as opposed to the left mouse button for thecallback function). You can associate functions with several other types of userevents as well; to learn more, see the online documentation, or experiment byclicking the right mouse button on various objects and on the grid behind themin the Layout Editor. Chapter 9ApplicationsIn this chapter, we present examples showing you how to apply MATLABto problems in several different disciplines. Each example is presented as aMATLAB M-book. These M-books are illustrations of the kinds of polished,integrated, interactive documents that you can create with MATLAB, as aug-mented by the Word interface. The M-books are:r Illuminating a Roomr Mortgage Paymentsr Monte Carlo Simulationr Population Dynamicsr Linear Economic Modelsr Linear Programmingr The 360◦Pendulumr Numerical Solution of the Heat Equationr A Model of Traffic FlowWe have not explained all the MATLAB commands that we use; you canlearn about the new commands from the online help. SIMULINK is used inA Model of Traffic Flow and as an optional accessory in Population Dynamicsand Numerical Solution of the Heat Equation. Running the M-book on LinearProgramming also requires an M-file found (in slightly different forms) in theSIMULINK and Optimization toolboxes.The M-books require different levels of mathematical background and ex-pertise in other subjects. Illuminating a Room, Mortgage Payments, andPopulation Dynamics use only high school mathematics. Monte Carlo Simula-tion uses some probability and statistics; Linear Economic Models and LinearProgramming, some linear algebra; The 360◦Pendulum, some ordinary dif-ferential equations; Numerical Solution of the Heat Equation, some partial136 Illuminating a Room 137differential equations; and A Model of Traffic Flow, differential equations, lin-ear algebra, and familiarity with the function ezfor z a complex number. Evenif you don't have the background for a particular example, you should be ableto learn something about MATLAB from the M-book.Illuminating a RoomSuppose we need to decide where to put light fixtures on the ceiling of aroom, measuring 10 meters by 4 meters by 3 meters high, in order to bestilluminate it. For aesthetic reasons, we are asked to use a small number ofincandescent bulbs. We want the bulbs to total a maximum of 300 watts. Fora given number of bulbs, how should they be placed to maximize theintensity of the light in the darkest part of the room? We also would like tosee how much improvement there is in going from one 300-watt bulb to two150-watt bulbs to three 100-watt bulbs, and so on. To keep things simple, weassume that there is no furniture in the room and that the light reflectedfrom the walls is insignificant compared with the direct light from thebulbs.One 300-Watt BulbIf there is only one bulb, then we want to put the bulb in the center of theceiling. Let's picture how well the floor is illuminated. We introducecoordinates x running from 0 to 10 in the long direction of the room and yrunning from 0 to 4 in the short direction. The intensity at a given point,measured in watts per square meter, is the power of the bulb, 300, divided by4π times the square of the distance from the bulb. Since the bulb is 3 metersabove the point (5, 2) on the floor, we can express the intensity at a point(x, y) on the floor as follows:syms x y; illum = 300/(4*pi*((x - 5)ˆ2 + (y - 2)ˆ2 + 3ˆ2))illum =75/pi/((x-5)ˆ2+(y-2)ˆ2+9)We can use ezcontourf to plot this expression over the entire floor. Weuse colormap to arrange for a color gradation that helps us to see the 138 Chapter 9: Applicationsillumination. (See the online help for graph3d for more colormap options.)ezcontourf(illum,[0 10 0 4]); colormap(gray);axis equal tight0 1 2 3 4 5 6 7 8 9 1000.511.522.533.54xy75/π/((x−5)2+(y−2)2+9)The darkest parts of the floor are the corners. Let us find the intensity of thelight at the corners, and at the center of the room.subs(illum, {x, y}, {0, 0})subs(illum, {x, y}, {5, 2})ans =0.6282ans =2.6526The center of the room, at floor level, is about 4 times as bright as thecorners when there is only one bulb on the ceiling. Our objective is to lightthe room more uniformly using more bulbs with the same total amount ofpower. Before proceeding to deal with multiple bulbs, we observe that theuse of ezcontourf is somewhat confining, as it does not allow us to controlthe number of contours in our pictures. Such control will be helpful in seeingthe light intensity; therefore we shall plot numerically rather thansymbolically; that is, we shall use contourf instead of ezcontourf.Two 150-Watt BulbsIn this case we need to decide where to put the two bulbs. Common sensetells us to arrange the bulbs symmetrically along a line down the center of Illuminating a Room 139the room in the long direction, that is, along the line y = 2. Define a functionthat gives the intensity of light at a point (x, y) on the floor due to a 150-wattbulb at a position (d, 2) on the ceiling.light2 = inline(vectorize('150/(4*pi*((x - d)ˆ2 + (y - 2)ˆ2 +3ˆ2))'), 'x', 'y', 'd')light2 =Inline function:light2(x,y,d) = 150./(4.*pi.*((x - d).ˆ2 + (y - 2).ˆ2 +3.ˆ2))Let's get an idea of the illumination pattern if we put one light at d = 3and the other at d = 7. We specify the drawing of 20 contours in this and thefollowing plots.[X,Y] = meshgrid(0:0.1:10, 0:0.1:4); contourf(light2(X, Y, 3)+ light2(X, Y, 7), 20); axis equal tight10 20 30 40 50 60 70 80 90 100510152025303540The floor is more evenly lit than with one bulb, but it looks as if the bulbsare closer together than they should be. If we move the bulbs further apart,the center of the room will get dimmer but the corners will get brigher. Let'stry changing the location of the lights to d = 2 and d = 8.contourf(light2(X, Y, 2) + light2(X, Y, 8), 20);axis equal tight 140 Chapter 9: Applications10 20 30 40 50 60 70 80 90 100510152025303540This is an improvement. The corners are still the darkest spots of theroom, though the light intensity along the walls toward the middle of theroom (near x = 5) is diminishing as we move the bulbs further apart. Tobetter illuminate the darkest spots we should keep moving the bulbs apart.Let's try lights at d = 1 and d = 9.contourf(light2(X, Y, 1) + light2(X, Y, 9), 20);axis equal tight10 20 30 40 50 60 70 80 90 100510152025303540Looking along the long walls, the room is now darker toward the middle thanat the corners. This indicates that we have spread the lights too far apart.We could proceed with further contour plots, but instead let's besystematic about finding the best position for the lights. In general, we canput one light at x = d and the other symmetrically at x = 10 − d for dbetween 0 and 5. Judging from the examples above, the darkest spots will be Illuminating a Room 141either at the corners or at the midpoints of the two long walls. By symmetry,the intensity will be the same at all four corners, so let's graph the intensityat one of the corners (0, 0) as a function of d.d = 0:0.1:5; plot(d, light2(0, 0, d) + light2(0, 0, 10 - d))0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 50.60.650.70.750.80.850.90.9511.05As expected, the smaller d is, the brighter the corners are. In contrast, thegraph for the intensity at the midpoint (5, 0) of a long wall (again bysymmetry it does not matter which of the two long walls we choose) shouldgrow as d increases toward 5.plot(d, light2(5, 0, d) + light2(5, 0, 10 - d))0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 50.60.811.21.41.61.82We are after the value of d for which the lower of the two numbers on theabove graphs (corresponding to the darkest spot in the room) is as high aspossible. We can find this value by showing both curves on one graph. Illuminating a Room 143The darkest spots in the room have intensity around 0.93, as opposed to 0.63for a single bulb. This represents an improvement of about 50%.Three 100-Watt BulbsWe redefine the intensity function for 100-watt bulbs:light3 = inline(vectorize('100/(4*pi*((x - d)ˆ2 + (y - 2)ˆ2 +3ˆ2))'), 'x', 'y', 'd')light3 =Inline function:light3(x,y,d) = 100./(4.*pi.*((x - d).ˆ2 + (y - 2).ˆ2 +3.ˆ2))Assume we put one bulb at the center of the room and place the other twosymmetrically as before. Here we show the illumination of the floor when theoff-center bulbs are one meter from the short walls.[X,Y] = meshgrid(0:0.1:10, 0:0.1:4); contourf(light3(X, Y, 1)+ light3(X, Y, 5) + light3(X, Y, 9), 20);axis equal tight10 20 30 40 50 60 70 80 90 100510152025303540It appears that we should put the bulbs even closer to the walls. (This maynot please everyone's aesthetics!) Let d be the distance of the bulbs from theshort walls. We define a function giving the intensity at position x along along wall and then graph the intensity as a function of d for several valuesof x. 144 Chapter 9: Applicationsd = 0:0.1:5;for x = 0:0.5:5plot(d, light3(x, 0, d) + light3(x, 0, 5) + ...light3(x, 0, 10 - d))hold onendhold off0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 50.60.811.21.41.61.82We know that for d near 5, the intensity will be increasing as x increasesfrom 0 to 5, so the bottom curve corresponds to x = 0 and the top curve tox = 5. Notice that the x = 0 curve is the lowest one for all d, and it rises as ddecreases. Thus d = 0 maximizes the intensity of the darkest spots in theroom, which are the corners (corresponding to x = 0). There the intensity isas follows:light3(0, 0, 0) + light3(0, 0, 5) + light3(0, 0, 10)ans =0.8920This is surprising; we do worse than with two bulbs. In going from twobulbs to three, with a decrease in wattage per bulb, we are forced to movewattage away from the ends of the room and bring it back to the center. Wecould probably improve on the two-bulb scenario if we used brighter bulbs atthe ends of the room and a dimmer bulb in the center, or if we used four75-watt bulbs. But our results so far indicate that the amount to be gained ingoing to more than two bulbs is likely to be small compared with the amountwe gained by going from one bulb to two. Mortgage Payments 145Mortgage PaymentsWe want to understand the relationships among the mortgage payment rateof a fixed rate mortgage, the principal (the amount borrowed), the annualinterest rate, and the period of the loan. We are going to assume (as isusually the case in the United States) that payments are made monthly,even though the interest rate is given as an annual rate. Let's defineperyear = 1/12; percent = 1/100;So the number of payments on a 30-year loan is30*12ans =360and an annual percentage rate of 8% comes out to a monthly rate of8*percent*peryearans =0.0067Now consider what happens with each monthly payment. Some of thepayment is applied to interest on the outstanding principal amount, P, andsome of the payment is applied to reduce the principal owed. The totalamount, R, of the monthly payment remains constant over the life of theloan. So if J denotes the monthly interest rate, we have R = J ∗ P + (amountapplied to principal), and the new principal after the payment is applied isP + J ∗ P − R = P ∗ (1 + J) − R = P ∗ m − R,where m = 1 + J. So a table of the amount of the principal still outstandingafter n payments is tabulated as follows for a loan of initial amount A, for nfrom 0 to 6:syms m J P R AP = A;for n = 0:6,disp([n, P]),P = simplify(-R + P*m);end 146 Chapter 9: Applications[ 0, A][ 1, -R+A*m][ 2, -R-m*R+A*mˆ2][ 3, -R-m*R-mˆ2*R+A*mˆ3][ 4, -R-m*R-mˆ2*R-mˆ3*R+A*mˆ4][ 5, -R-m*R-mˆ2*R-mˆ3*R-mˆ4*R+A*mˆ5][ 6, -R-m*R-mˆ2*R-mˆ3*R-mˆ4*R-mˆ5*R+A*mˆ6]We can write this in a simpler way by noticing that P = A∗ mn+ (termsdivisible by R). For example, with n = 7 we havefactor(p - A*mˆ7)ans =-R*(1+m+mˆ2+mˆ3+mˆ4+mˆ5+mˆ6)But the quantity inside the parentheses is the sum of a geometric seriesn−1k=1mk=mn− 1m− 1.So we see that the principal after n payments can be written asP = A∗ mn− R∗ (mn− 1)/(m− 1).Now we can solve for the monthly payment amount R under the assumptionthat the loan is paid off in N installments, that is, P is reduced to 0 after Npayments:syms N; solve(A*mˆN - R*(mˆN - 1)/(m - 1), R)ans =A*mˆN*(m-1)/(mˆN-1)R = subs(ans, m, J + 1)R=A*(J+1)ˆN*J/((J+1)ˆN-1)For example, with an initial loan amount A = $150,000 and a loan lifetimeof 30 years (360 payments), we get the following table of payment amountsas a function of annual interest rate: Monte Carlo Simulation 149solve(A*mˆN - R*(mˆN - 1)/(m - 1), A)ans =R*(mˆN-1)/(mˆN)/(m-1)For example, if one is shopping for a house and can afford to pay $1500 permonth for a 30-year fixed-rate mortgage, the maximum loan amount as afunction of the interest rate is given bydisp(' Interest Rate Loan Amt.')for rate = 1:10,disp([rate, double(subs(ans, [R, N, m], [1500, 360,...1 + rate*percent*peryear]))])endInterest Rate Loan Amt.1.00 466360.602.00 405822.773.00 355784.074.00 314191.865.00 279422.436.00 250187.427.00 225461.358.00 204425.249.00 186422.8010.00 170926.23Monte Carlo SimulationIn order to make statistical predictions about the long-term results of arandom process, it is often useful to do a simulation based on one'sunderstanding of the underlying probabilities. This procedure is referred toas the Monte Carlo method.As an example, consider a casino game in which a player bets against thehouse and the house wins 51% of the time. The question is: How manygames have to be played before the house is reasonably sure of coming outahead? This scenario is common enough that mathematicians long agofigured out very precisely what the statistics are, but here we want toillustrate how to get a good idea of what can happen in practice withouthaving to absorb a lot of mathematics. 150 Chapter 9: ApplicationsFirst we construct an expression that computes the net revenue to thehouse for a single game, based on a random number chosen between 0 and 1by the MATLAB function rand. If the random number is less than or equalto 0.51, the house wins one betting unit, whereas if the number exceeds 0.51,the house loses one unit. (In a high-stakes game, each bet may be worth$1000 or more. Thus it is important for the casino to know how bad a losingstreak it may have to weather to turn a profit — so that it doesn't gobankrupt first!) Here is an expression that returns 1 if the output of rand isless than 0.51 and −1 if the output of rand is greater than 0.51 (it will alsoreturn 0 if the output of rand is exactly 0.51, but this is extremely unlikely):revenue = sign(0.51 - rand)revenue =-1In the game simulated above, the house lost. To simulate several games atonce, say 10 games, we can generate a vector of 10 random numbers with thecommand rand(1, 10) and then apply the same operation.revenues = sign(0.51 - rand(1, 10))revenues =1 -1 1 -1 -1 1 1 -1 1 -1In this case the house won 5 times and lost 5 times, for a net profit of 0 units.For a larger number of games, say 100, we can let MATLAB sum the revenuefrom the individual bets as follows:profit = sum(sign(0.51 - rand (1, 100)))profit =-4For this trial, the house had a net loss of 4 units after 100 games. Onaverage, every 100 games the house should win 51 times and the player(s)should win 49 times, so the house should make a profit of 2 units (onaverage). Let's see what happens in a few trial runs.profits = sum(sign(0.51 - rand(100, 10)))profits =14 -12 6 2 -4 0 -10 12 0 12 Monte Carlo Simulation 151We see that the net profit can fluctuate significantly from one set of 100games to the next, and there is a sizable probability that the house has lostmoney after 100 games. To get an idea of how the net profit is likely to bedistributed in general, we can repeat the experiment a large number of timesand make a histogram of the results. The following function computes thenet profits for k different trials of n games each:profits = inline('sum(sign(0.51 - rand(n, k)))', 'n', 'k')profits =Inline function:profits(n,k) = sum(sign(0.51 - rand(n, k)))What this function does is to generate an n × k matrix of randomnumbers and then perform the same operations as above on each entry ofthe matrix to obtain a matrix with entries 1 for bets the house won and −1for bets it lost. Finally it sums the columns of the matrix to obtain a rowvector of k elements, each of which represents the total profit from acolumn of n bets.Now we make a histogram of the output of profits using n = 100 andk = 100. Theoretically the house could win or lose up to 100 units, but inpractice we find that the outcomes are almost always within 30 or so of 0.Thus we let the bins of the histogram range from −40 to 40 in increments of2 (since the net profit is always even after 100 bets).hist(profits(100, 100), -40:2:40); axis tight−40 −30 −20 −10 0 10 20 30 40024681012 152 Chapter 9: ApplicationsThe histogram confirms our impression that there is a wide variation in theoutcomes after 100 games. The house is about as likely to have lost moneyas to have profited. However, the distribution shown above is irregularenough to indicate that we really should run more trials to see a betterapproximation to the actual distribution. Let's try 1000 trials.hist(profits(100, 1000), -40:2:40); axis tight−40 −30 −20 −10 0 10 20 30 4001020304050607080According to the Central Limit Theorem, when both n and k are large, thehistogram should be shaped like a "bell curve", and we begin to see thisshape emerging above. Let's move on to 10,000 trials.hist(profits(100, 10000), -40:2:40); axis tight−40 −30 −20 −10 0 10 20 30 400100200300400500600700 Monte Carlo Simulation 153Here we see very clearly the shape of a bell curve. Though we haven't gainedthat much in terms of knowing how likely the house is to be behind after 100games, and how large its net loss is likely to be in that case, we do gainconfidence that our results after 1000 trials are a good depiction of thedistribution of possible outcomes.Now we consider the net profit after 1000 games. We expect on averagethe house to win 510 games and the player(s) to win 490, for a net profit of 20units. Again we start with just 100 trials.hist(profits(1000, 100), -100:10:150); axis tight−100 −50 0 50 100 150051015Though the range of observed values for the profit after 1000 games islarger than the range for 100 games, the range of possible values is 10 timesas large, so that relatively speaking the outcomes are closer together thanbefore. This reflects the theoretical principle (also a consequence of theCentral Limit Theorem) that the average "spread" of outcomes after a largenumber of trials should be proportional to the square root of n, the number ofgames played in each trial. This is important for the casino, since if thespread were proportional to n, then the casino could never be too sure ofmaking a profit. When we increase n by a factor of 10, the spread should onlyincrease by a factor of√10, or a little more than 3.Note that after 1000 games, the house is definitely more likely to be aheadthan behind. However, the chances of being behind are still sizable. Let'srepeat with 1000 trials to be more certain of our results.hist(profits(1000, 1000), -100:10:150); axis tight 154 Chapter 9: Applications−100 −50 0 50 100 150050100150We see the bell curve shape emerging again. Though it is unlikely, thechances are not insignificant that the house is behind by more than 50 unitsafter 1000 games. If each unit is worth $1000, then we might advise thecasino to have at least $100,000 cash on hand to be prepared for thispossibility. Maybe even that is not enough — to see we would have toexperiment further.Finally, let's see what happens after 10,000 games. We expect on averagethe house to be ahead by 200 units at this point, and based on our earlierdiscussion the range of values we use to make the histogram need only go upby a factor of 3 or so from the previous case. Even 100 trials will take a whileto run now, but we have to start somewhere.hist(profits(10000, 100), -200:25:600); axis tight−200 −100 0 100 200 300 400 500 600024681012141618 Monte Carlo Simulation 155It seems that turning a profit after 10,000 games is highly likely, althoughwith only 100 trials we do not get such a good idea of the worst-casescenario. Though it will take a good bit of time, we should certainly do1000 trials or more if we are considering putting our money into such aventure.hist(profits(10000, 1000), -200:25:600); axis tight??? Error using ==> inlineevalError in inline expression ==> sum(sign(0.51 - rand(n, k)))??? Error using ==> -Out of memory. Type HELP MEMORY for your options.Error in ==>C:MATLABR12toolboxmatlabfunfun@inlinesubsref.mOn line 25 ==> INLINE OUT = inlineeval(INLINE INPUTS ,INLINE OBJ .inputExpr, INLINE OBJ .expr);This error message illustrates a potential hazard in using MATLAB's vectorand matrix operations in place of a loop: In this case the matrix rand(n,k)generated within the profits function must fit in the memory of thecomputer. Since n is 10,000 and k is 1000 in our most recent attempt to runthis function, we requested a matrix of 10,000,000 random numbers. Eachfloating point number in MATLAB takes up 8 bytes of memory, so the matrixwould have required 80MB to store, which is too much for some computers.Since k represents a number of trials that can be done independently, asolution to the memory problem is to break the 1000 trials into 10 groupsof 100, using a loop to run 100 trials 10 times and assemble theresults.profitvec = [];for i = 1:10profitvec = [profitvec profits(10000, 100)];endhist(profitvec, -200:25:600); axis tight 156 Chapter 9: Applications−200 −100 0 100 200 300 400 500 6000102030405060708090100Though the chances of a loss after 10,000 games is quite small, thepossibility cannot be ignored, and we might judge that the house should notrule out being behind at some point by 100 or more units. However, theoverall upward trend seems clear, and we may expect that after 100,000games the casino is overwhelmingly likely to have made a profit. Based onour previous observations of the growth of the spread of outcomes, we expectthat most of the time the net profit will be within 1000 of the expected valueof 2000. We show the results of 10 trials of 100,000 games below.profits(100000, 10)ans =Columns 1 through 62294 1946 2652 2630 18722078Columns 7 through 101984 1552 2138 1852Population DynamicsWe are going to look at two models for population growth of a species. Thefirst is a standard exponential growth and decay model that describes quitewell the population of a species becoming extinct, or the short-term behaviorof a population growing in an unchecked fashion. The second, more realistic Population Dynamics 157model, describes the growth of a species subject to constraints of space, foodsupply, competitors, and predators.Exponential Growth and DecayWe assume that the species starts with an initial population P0. Thepopulation after n times units is denoted Pn. Suppose that in each timeinterval, the population increases or decreases by a fixed proportion of itsvalue at the begining of the interval. Thus Pn = Pn−1 + rPn−1, n ≥ 1. Theconstant r represents the difference between the birth rate and the deathrate. The population increases if r is positive, decreases if r is negative, andremains fixed if r = 0.Here is a simple M-file that will compute the population at stage n, giventhe population at the previous stage and the rate r:function X = itseq(f, Xinit, n, r)% computing an iterative sequence of valuesX = zeros(n + 1, 1);X(1) = Xinit;for i = 1:nX(i + 1) = f(X(i), r);endIn fact, this is a simple program for computing iteratively the values of asequence an = f (an−1), n ≥ 1, provided you have previously entered theformula for the function f and the initial value of the sequence a0. Note theextra parameter r built into the algorithm.Now let's use the program to compute two populations at five-yearintervals for different values of r:r = 0.1; Xinit = 100; f = inline('x*(1 + r)', 'x', 'r');X = itseq(f, Xinit, 100, r);format long; X(1:5:101)ans =1.0e+006 *0.000100000000000.000161051000000.000259374246010.00041772481694 Population Dynamics 1590.000129007007820.000076177348050.000044981962250.00002656139889In the first case, the population is growing rapidly; in the second, it isdecaying rapidly. In fact, it is clear from the model that, for any n, thequotient Pn+1/Pn = (1 + r), and therefore it follows that Pn = P0(1 + r)n, n ≥ 0.This accounts for the expression exponential growth and decay. The modelpredicts a population growth without bound (for growing populations) and istherefore not realistic. Our next model allows for a check on the populationcaused by limited space, limited food supply, competitors and predators.Logistic GrowthThe previous model assumes that the relative change in population isconstant, that is,(Pn+1 − Pn)/Pn = r.Now let's build in a term that holds down the growth, namely(Pn+1 − Pn)/Pn = r − uPn.We shall simplify matters by assuming that u = 1 + r, so that our recursionrelation becomesPn+1 = uPn(1 − Pn),where u is a positive constant. In this model, the population P is constrainedto lie between 0 and 1, and should be interpreted as a percentage of amaximum possible population in the environment in question. So let us setup the function we will use in the iterative procedure:clear f; f = inline('u*x*(1 - x)', 'x', 'u');Now let's compute a few examples; and use plot to display the results.u = 0.5; Xinit = 0.5; X = itseq(f, Xinit, 20, u); plot(X) Population Dynamics 161u = 3.4; X = itseq(f, Xinit, 20, u); plot(X)0 5 10 15 20 250.40.450.50.550.60.650.70.750.80.850.9In the first computation, we have used our iterative program to computethe population density for 20 time intervals, assuming a logistic growthconstant u = 0.5 and an initial population density of 50%. The populationseems to be dying out. In the remaining examples, we kept the initialpopulation density at 50%; the only thing we varied was the logistic growthconstant. In the second example, with a growth constant u = 1, once againthe population is dying out — although more slowly. In the third example,with a growth constant of 1.5 the population seems to be stabilizing at33.3...%. Finally, in the last example, with a constant of 3.4 the populationseems to oscillate between densities of approximately 45% and 84%.These examples illustrate the remarkable features of the logisticpopulation dynamics model. This model has been studied for more than 150years, with its origins lying in an analysis by the Belgian mathematicianPierre Verhulst. Here are some of the facts associated with this model. Wewill corroborate some of them with MATLAB. In particular, we shall use baras well as plot to display some of the data.(1) The Logistic Constant Cannot Be Larger Than 4For the model to work, the output at any point must be between 0 and 1. Butthe parabola ux(1 − x), for 0 ≤ x ≤ 1, has its maximum height when x = 1/2,where its value is u/4. To keep that number between 0 and 1, we mustrestrict u to be at most 4. Here is what happens if u is bigger than 4: Population Dynamics 1650 10 20 30 40 50 60 70 80 90 10000.10.20.30.40.50.60.70.80.9(5) There Is a Value u < 4 Beyond Which Chaos EnsuesIt is possible to prove that the sequence uk tends to a limit u∞. The value ofu∞, sometimes called the Feigenbaum parameter, is aproximately 3.56994... .Let's see what happens if we use a value of u between the Feigenbaumparameter and 4.X = itseq(f, 0.75, 100, 3.7); plot(X)0 20 40 60 80 100 1200.20.30.40.50.60.70.80.91This is an example of what mathematicians call a chaotic phenomenon! Itis not random — the sequence was generated by a precise, fixedmathematical procedure — but the results manifest no predictible pattern.Chaotic phenomena are unpredictable, but with modern methods (includingcomputer analysis), mathematicians have been able to identify certainpatterns of behavior in chaotic phenomena. For example, the last figure 166 Chapter 9: Applicationssuggests the possibility of unstable periodic cycles and other recurringphenomena. Indeed a great deal of information is known. Theaforementioned book by Gulick is a fine reference, as well as the source of anexcellent bibliography on the subject.Rerunning the Model with SIMULINKThe logistic growth model that we have been exploring lends itselfparticularly well to simulation using SIMULINK. Here is a simpleSIMULINK model that corresponds to the above calculations:z1Unit DelayScopeProduct3.7LogisticConstantDiscrete PulseGenerator1 1u1−xxxLet's briefly explain how this works. If you ignore the Discrete PulseGenerator block and the Sum block in the lower left for a moment, thismodel implements the equationx at next time = ux(1 − x) at old time,which is the equation for the logistic model. The Scope block displays a plotof x as a function of (discrete) time. However, we need somehow to build inthe initial condition for x. The simplest way to do this is as illustrated here:We add to the right-hand side a discrete pulse that is the initial value of x attime t = 0 and is 0 thereafter. Since the model is discrete, you can achievethis by setting the period of the Discrete Pulse Generator block to somethinglonger than the length of the simulation, and setting the width of the pulse Population Dynamics 167to 1 and the amplitude of the pulse to the initial value of x. The outputsfrom the model in the two interesting cases of u = 3.4 and u = 3.7 are shownhere:In the first case of u = 3.4, the periodic behavior is clearly visible. However,when u = 3.7, we get chaotic behavior. 168 Chapter 9: ApplicationsLinear Economic ModelsMATLAB's linear algebra capabilities make it a good vehicle for studyinglinear economic models, sometimes called Leontief models (after theirprimary developer, Nobel Prize-winning economist Wassily Leontief) orinput-output models. We will give a few examples. The simplest such modelis the linear exchange model or closed Leontief model of an economy. Thismodel supposes that an economy is divided into, say, n sectors, such asagriculture, manufacturing, service, consumers, etc. Each sector receivesinput from the various sectors (including itself) and produces an output,which is divided among the various sectors. (For example, agricultureproduces food for home consumption and for export, but also seeds and newlivestock, which are reinvested in the agricultural sector, as well aschemicals that may be used by the manufacturing sector, and so on.) Themeaning of a closed model is that total production is equal to totalconsumption. The economy is in equilibrium when each sector of theeconomy (at least) breaks even. For this to happen, the prices of the variousoutputs have to be adjusted by market forces. Let aij denote the fraction ofthe output of the jth sector consumed by the ith sector. Then the aij are theentries of a square matrix, called the exchange matrix A, each of whosecolumns sums to 1. Let pi be the price of the output of the ith sector of theeconomy. Since each sector is to at least break even, pi cannot be smallerthan the value of the inputs consumed by the ith sector, or in other words,pi ≥jaij pj.But summing over i and using the fact that i aij = 1, we see that both sidesmust be equal. In matrix language, that means that (I − A)p = 0, where p isthe column vector of prices. Thus p is an eigenvector of A for the eigenvalue1, and the theory of stochastic matrices implies (assuming that A isirreducible, meaning that there is no proper subset E of the sectors of theeconomy such that outputs from E all stay inside E) that p is uniquelydetermined up to a scalar factor. In other words, a closed irreducible lineareconomy has an essentially unique equilibrium state. For example, if wehaveA = [.3, .1, .05, .2; .1, .2, .3, .3; .3, .5, .2, .3; .3,.2, .45, .2] Linear Economic Models 169A =0.3000 0.1000 0.0500 0.20000.1000 0.2000 0.3000 0.30000.3000 0.5000 0.2000 0.30000.3000 0.2000 0.4500 0.2000then as required,sum(A)ans =1 1 1 1That is, all the columns sum to 1, and[V, D] = eig(A); D(1, 1)p = V(:, 1)ans =1.0000p =0.27390.47680.61330.5669shows that 1 is an eigenvalue of A with price eigenvector p as shown.Somewhat more realistic is the (static, linear) open Leontief model of aneconomy, which takes labor, consumption, etc., into account. Let's illustratewith an example. The following cell inputs an actual input-outputtransactions table for the economy of the United Kingdom in 1963. (Thistable is taken from Input-Output Analysis and its Applications byR. O'Connor and E. W. Henry, Hafner Press, New York, 1975.) Tables suchas this one can be obtained from official government statistics. The table Tis a 10 × 9 matrix. Units are millions of British pounds. The rows representrespectively, agriculture, industry, services, total inter-industry, imports,sales by final buyers, indirect taxes, wages and profits, total primary inputs,and total inputs. The columns represent, respectively, agriculture, industry,services, total inter-industry, consumption, capital formation, exports, totalfinal demand, and output. Thus outputs from each sector can be read offalong a row, and inputs into a sector can be read off along a column. 172 Chapter 9: Applicationsfact that the last column of T is the sum of columns 4 (total inter-industryoutputs) and 8 (total final demand) translates into the matrix equationX = AX + Y, or Y = (1 − A)X. Let's check this:Y = T(1:3, 8); X = T(1:3, 9); Y - (eye(3) - A)*Xans =000Now one can do various numerical experiments. For example, what wouldbe the effect on output of an increase of £10 billion (10,000 in the units ofour problem) in final demand for industrial output, with no correspondingincrease in demand for services or for agricultural products? Since theeconomy is assumed to be linear, the change X in X is obtained by solvingthe linear equation Y = (1 − A) X, anddeltaX = (eye(3) - A) [0; 10000; 0]deltaX =1.0e+004 *0.02801.62650.1754Thus agricultural output would increase by £280 million, industrial outputwould increase by £16.265 billion, and service output would increase by£1.754 billion. We can illustrate the result of doing this for similar increasesin demand for the other sectors with the following pie charts:deltaX1 = (eye(3) - A) [10000; 0; 0];deltaX2 = (eye(3) - A) [0; 0; 10000];subplot(1, 3, 1), pie(deltaX1, {'Agr.', 'Ind.', 'Serv.'}),subplot(1, 3, 2), pie(deltaX, {'Agr.', 'Ind.', 'Serv.'}),title('Effect of increases in demand for each of the 3sectors', 'FontSize',18),subplot(1, 3, 3), pie(deltaX2, {'Agr.', 'Ind.', 'Serv.'}); Linear Programming 173Agr.Ind.Serv. Agr.Ind.Serv.Effect of increases in demand for each of the 3 sectorsAgr.Ind.Serv.Linear ProgrammingMATLAB is ideally suited to handle linear programming problems. Theseare problems in which you have a quantity, depending linearly on severalvariables, that you want to maximize or minimize subject to severalconstraints that are expressed as linear inequalities in the same variables. Ifthe number of variables and the number of constraints are small, then thereare numerous mathematical techniques for solving a linear programmingproblem — indeed these techniques are often taught in high school oruniversity courses in finite mathematics. But sometimes these numbers arehigh, or even if low, the constants in the linear inequalities or the objectexpression for the quantity to be optimized may be numericallycomplicated — in which case a software package like MATLAB is required toeffect a solution. We shall illustrate the method of linear programming bymeans of a simple example, giving a combination graphical-numericalsolution, and then solve both a slightly and a substantially more complicatedproblem.Suppose a farmer has 75 acres on which to plant two crops: wheat andbarley. To produce these crops, it costs the farmer (for seed, fertilizer, etc.)$120 per acre for the wheat and $210 per acre for the barley. The farmer has$15,000 available for expenses. But after the harvest, the farmer must storethe crops while awaiting favorable market conditions. The farmer has 174 Chapter 9: Applicationsstorage space for 4,000 bushels. Each acre yields an average of 110 bushelsof wheat or 30 bushels of barley. If the net profit per bushel of wheat (afterall expenses have been subtracted) is $1.30 and for barley is $2.00, howshould the farmer plant the 75 acres to maximize profit?We begin by formulating the problem mathematically. First we expressthe objective, that is, the profit, and the constraints algebraically, then wegraph them, and lastly we arrive at the solution by graphical inspection anda minor arithmetic calculation.Let x denote the number of acres allotted to wheat and y the number ofacres allotted to barley. Then the expression to be maximized, that is, theprofit, is clearlyP = (110)(1.30)x + (30)(2.00)y = 143x + 60y.There are three constraint inequalities, specified by the limits on expenses,storage, and acreage. They are respectively120x + 210y ≤ 15,000110x + 30y ≤ 4,000x + y ≤ 75.Strictly speaking there are two more constraint inequalities forced by thefact that the farmer cannot plant a negative number of acres, namely,x ≥ 0, y ≥ 0.Next we graph the regions specified by the constraints. The last two saythat we only need to consider the first quadrant in the x-y plane. Here's agraph delineating the triangular region in the first quadrant determined bythe first inequality.X = 0:125;Y1 = (15000 - 120.*X)./210;area(X, Y1) Linear Programming 177y =425/8double([x, y])ans =21.8750 53.1250The acreage that results in the maximum profit is 21.875 for wheat and53.125 for barley. In that case the profit isP = 143*x + 60*yP=50525/8format bank; double(P)ans =6315.63that is, $6,315.63.This problem illustrates and is governed by the Fundamental Theorem ofLinear Programming, stated here in two variables:A linear expression ax + by, defined over a closed bounded convex setS whose sides are line segments, takes on its maximum value at avertex of S and its minimum value at a vertex of S. If S is unbounded,there may or may not be an optimum value, but if there is, it occurs at avertex. (A convex set is one for which any line segment joining twopoints of the set lies entirely inside the set.)In fact the SIMULINK toolbox has a built-in function, simlp, thatimplements the solution of a linear programming problem. The optimizationtoolbox has an almost identical function called linprog. You can learnabout either one from the online help. We will use simlp on the aboveproblem. After that we will use it to solve two more complicated problemsinvolving more variables and constraints. Here is the beginning of theoutput from help simlp:SIMLP Helper function for GETXO; solves linear programmingproblem. Linear Programming 179-1 0 0; 0 -1 0; 0 0 -1];b = [15000; 4000; 75; 0; 0; 0];simlp(f, A, b)ans =0.000056.578918.4211So the farmer should ditch the wheat and plant 56.5789 acres of barley and18.4211 acres of corn.There is no practical limit on the number of variables and constraints thatMATLAB can handle — certainly none that the relatively unsophisticateduser will encounter. Indeed, in many true applications of the technique oflinear programming, one needs to deal with many variables and constraints.The solution of such a problem by hand is not feasible, and software such asMATLAB is crucial to success. For example, in the farming problem withwhich we have been working, one could have more than two or three crops.(Think agribusiness instead of family farmer.) And one could haveconstraints that arise from other things besides expenses, storage, andacreage limitations, for example:r Availability of seed. This might lead to constraint inequalities such asxj ≤ k.r Personal preferences. Thus the farmer's spouse might have a preferencefor one variety or group of varieties over another, and insist on acorresponding planting, thus leading to constraint inequalities such asxi ≤ xj or x1 + x2 ≥ x3.r Government subsidies. It may take a moment's reflection on thereader's part, but this could lead to inequalities such as xj ≥ k.Below is a sequence of commands that solves exactly such a problem. Youshould be able to recognize the objective expression and the constraints fromthe data that are entered. But as an aid, you might answer the followingquestions:r How many crops are under consideration?r What are the corresponding expenses? How much money is availablefor expenses?r What are the yields in each case? What is the storage capacity?r How many acres are available? The 360˚ Pendulum 181it can swing through larger angles, even making a 360◦rotation if givenenough velocity.Though it is not precisely correct in practice, we often assume that themagnitude of the frictional forces that eventually slow the pendulum to ahalt is proportional to the velocity of the pendulum. Assume also that thelength of the pendulum is 1 meter, the weight at the end of the pendulumhas mass 1 kg, and the coefficient of friction is 0.5. In that case, theequations of motion for the pendulum arex (t) = y(t), y (t) = −0.5y(t) − 9.81 sin(x(t)),where t represents time in seconds, x represents the angle of the pendulumfrom the vertical in radians (so that x = 0 is the rest position), y representsthe velocity of the pendulum in radians per second, and 9.81 isapproximately the acceleration due to gravity in meters per second squared.Here is a phase portrait of the solution with initial position x(0) = 0 andinitial velocity y(0) = 5. This is a graph of x versus y as a function of t, on thetime interval 0 ≤ t ≤ 20.g = inline('[x(2); -0.5*x(2) - 9.81*sin(x(1))]', 't', 'x');[t, xa] = ode45(g, [0 20], [0 5]);plot(xa(:, 1), xa(:, 2))−1.5 −1 −0.5 0 0.5 1 1.5 2−4−3−2−1012345Recall that the x coordinate corresponds to the angle of the pendulum andthe y coordinate corresponds to its velocity. Starting at (0, 5), as t increaseswe follow the curve as it spirals clockwise toward (0, 0). The angle oscillatesback and forth, but with each swing it gets smaller until the pendulum isvirtually at rest by the time t = 20. Meanwhile the velocity oscillates as well,taking its maximum value during each oscillation when the pendulum is in 182 Chapter 9: Applicationsthe middle of its swing (the angle is near zero) and crossing zero when thependulum is at the end of its swing.Next we increase the initial velocity to 10.[t, xa] = ode45(g, [0 20], [0 10]);plot(xa(:, 1), xa(:, 2))0 5 10 15−50510This time the angle increases to over 14 radians before the curve spirals in toa point near (12.5, 0). More precisely, it spirals toward (4π, 0), because 4πradians represents the same position for the pendulum as 0 radians does.The pendulum has swung overhead and made two complete revolutionsbefore beginning its damped oscillation toward its rest position. The velocityat first decreases but then rises after the angle passes through π, as thependulum passes the upright position and gains momentum. The pendulumhas just enough momentum to swing through the upright position once moreat the angle 3π.Now suppose we want to find, to within 0.1, the minimum initial velocityrequired to make the pendulum, starting from its rest position, swingoverhead once. It will be useful to be able to see the solutions correspondingto several different initial velocities on one graph.First we consider the integer velocities 5 to 10.hold onfor a = 5:10[t, xa] = ode45(g, [0 20], [0 a]);plot(xa(:, 1), xa(:, 2))endhold off 184 Chapter 9: Applicationsplot(xa(:, 1), xa(:, 2))endhold off−2 0 2 4 6 8 10 12 14 16−6−4−20246810We conclude that the minimum velocity needed is somewhere between 7.25and 7.3.Numerical Solution of theHeat EquationIn this section we will use MATLAB to numerically solve the heat equation(also known as the diffusion equation), a partial differential equation thatdescribes many physical processes including conductive heat flow or thediffusion of an impurity in a motionless fluid. You can picture the process ofdiffusion as a drop of dye spreading in a glass of water. (To a certain extentyou could also picture cream in a cup of coffee, but in that case the mixing isgenerally complicated by the fluid motion caused by pouring the cream intothe coffee and is further accelerated by stirring the coffee.) The dye consistsof a large number of individual particles, each of which repeatedly bouncesoff of the surrounding water molecules, following an essentially randompath. There are so many dye particles that their individual random motionsform an essentially deterministic overall pattern as the dye spreads evenlyin all directions (we ignore here the possible effect of gravity). In a similarway, you can imagine heat energy spreading through random interactions ofnearby particles.In a three-dimensional medium, the heat equation is∂u∂t= k∂2u∂x2+∂2u∂y2+∂2u∂z2. Numerical Solution of the Heat Equation 185Here u is a function of t, x, y, and z that represents the temperature, orconcentration of impurity in the case of diffusion, at time t at position (x, y, z)in the medium. The constant k depends on the materials involved; it iscalled the thermal conductivity in the case of heat flow and the diffusioncoefficient in the case of diffusion. To simplify matters, let us assume that themedium is instead one-dimensional. This could represent diffusion in a thinwater-filled tube or heat flow in a thin insulated rod or wire; let us thinkprimarily of the case of heat flow. Then the partial differential equationbecomes∂u∂t= k∂2u∂x2,where u(x, t) is the temperature at time t a distance x along the wire.A Finite Difference SolutionTo solve this partial differential equation we need both initial conditions ofthe form u(x, 0) = f (x), where f (x) gives the temperature distribution in thewire at time 0, and boundary conditions at the endpoints of the wire; callthem x = a and x = b. We choose so-called Dirichlet boundary conditionsu(a, t) = Ta and u(b, t) = Tb, which correspond to the temperature being heldsteady at values Ta and Tb at the two endpoints. Though an exact solution isavailable in this scenario, let us instead illustrate the numerical method offinite differences.To begin with, on the computer we can only keep track of the temperatureu at a discrete set of times and a discrete set of positions x. Let the times be0, t, 2 t, . . . , N t, and let the positions be a, a + x, . . . , a + J x = b, andlet unj = u(a + j t, n t). Rewriting the partial differential equation in termsof finite-difference approximations to the derivatives, we getun+1j − unjt= kunj+1 − 2unj + unj−1x2.(These are the simplest approximations we can use for the derivatives, andthis method can be refined by using more accurate approximations,especially for the t derivative.) Thus if for a particular n, we know the valuesof unj for all j, we can solve the equation above to find un+1j for each j:un+1j = unj +k tx2unj+1 − 2unj + unj−1 = s unj+1 + unj−1 + (1 − 2s)unj,where s = k t/( x)2. In other words, this equation tells us how to find thetemperature distribution at time step n + 1 given the temperature 186 Chapter 9: Applicationsdistribution at time step n. (At the endpoints j = 0 and j = J, this equationrefers to temperatures outside the prescribed range for x, but at these pointswe will ignore the equation above and apply the boundary conditionsinstead.) We can interpret this equation as saying that the temperature at agiven location at the next time step is a weighted average of its temperatureand the temperatures of its neighbors at the current time step. In otherwords, in time t, a given section of the wire of length x transfers to eachof its neighbors a portion s of its heat energy and keeps the remainingportion 1 − 2s of its heat energy. Thus our numerical implementation of theheat equation is a discretized version of the microscopic description ofdiffusion we gave initially, that heat energy spreads due to randominteractions between nearby particles.The following M-file, which we have named heat.m, iterates theprocedure described above:function u = heat(k, x, t, init, bdry)% solve the 1D heat equation on the rectangle described by% vectors x and t with u(x, t(1)) = init and Dirichlet%dt/dxˆ2;u = zeros(N,J);u(1, :) = init;for n = 1:N-1u(n+1, 2:J-1) = s*(u(n, 3:J) + u(n, 1:J-2)) +...(1 - 2*s)*u(n, 2:J-1);u(n+1, 1) = bdry(1);u(n+1, J) = bdry(2);endThe function heat takes as inputs the value of k, vectors of t and x values, avector init of initial values (which is assumed to have the same length asx), and a vector bdry containing a pair of boundary values. Its output is amatrix of u values. Notice that since indices of arrays in MATLAB must startat 1, not 0, we have deviated slightly from our earlier notation by letting n=1 Numerical Solution of the Heat Equation 187represent the initial time and j=1 represent the left endpoint. Notice alsothat in the first line following the for statement, we compute an entire rowof u, except for the first and last values, in one line; each term is a vector oflength J-2, with the index j increased by 1 in the term u(n,3:J) anddecreased by 1 in the term u(n,1:J-2).Let's use the M-file above to solve the one-dimensional heat equation withk = 2 on the interval −5 ≤ x ≤ 5 from time 0 to time 4, using boundarytemperatures 15 and 25, and initial temperature distribution of 15 for x < 0and 25 for x > 0. You can imagine that two separate wires of length 5 withdifferent temperatures are joined at time 0 at position x = 0, and each oftheir far ends remains in an environment that holds it at its initialtemperature. We must choose values for t and x; let's try t = 0.1 andx = 0.5, so that there are 41 values of t ranging from 0 to 4 and 21 valuesof x ranging from −5 to 5.tvals = linspace(0, 4, 41);xvals = linspace(-5, 5, 21);init = 20 + 5*sign(xvals);uvals = heat(2, xvals, tvals, init, [15 25]);surf(xvals, tvals, uvals)xlabel x; ylabel t; zlabel u−50501234−1−0.500.51x 1012xtu 188 Chapter 9: ApplicationsHere we used surf to show the entire solution u(x, t). The output is clearlyunrealistic; notice the scale on the u axis! The numerical solution of partialdifferential equations is fraught with dangers, and instability like that seenabove is a common problem with finite difference schemes. For many partialdifferential equations a finite difference scheme will not work at all, but forthe heat equation and similar equations it will work well with proper choiceof t and x. One might be inclined to think that since our choice of x waslarger, it should be reduced, but in fact this would only make matters worse.Ultimately the only parameter in the iteration we're using is the constant s,and one drawback of doing all the computations in an M-file as we did aboveis that we do not automatically see the intermediate quantities it computes.In this case we can easily calculate that s = 2(0.1)/(0.5)2= 0.8. Notice thatthis implies that the coefficient 1 − 2s of unj in the iteration above is negative.Thus the "weighted average" we described before in our interpretation of theiterative step is not a true average; each section of wire is transferring moreenergy than it has at each time step!The solution to the problem above is thus to reduce the time step t; forinstance, if we cut it in half, then s = 0.4, and all coefficients in the iterationare positive.tvals = linspace(0, 4, 81);uvals = heat(2, xvals, tvals, init, [15 25]);surf(xvals, tvals, uvals)xlabel x; ylabel t; zlabel u−50501234152025xtu Numerical Solution of the Heat Equation 189This looks much better! As time increases, the temperature distributionseems to approach a linear function of x. Indeed u(x, t) = 20 + x isthe limiting "steady state" for this problem; it satisfies the boundaryconditions and it yields 0 on both sides of the partial differentialequation.Generally speaking, it is best to understand some of the theory of partialdifferential equations before attempting a numerical solution like we havedone here. However, for this particular case at least, the simple rule ofthumb of keeping the coefficients of the iteration positive yields realisticresults. A theoretical examination of the stability of this finite differencescheme for the one-dimensional heat equation shows that indeed any valueof s between 0 and 0.5 will work, and it suggests that the best value of t touse for a given x is the one that makes s = 0.25. (See Partial DifferentialEquations: An Introduction, by Walter A. Strauss, John Wiley and Sons,1992.) Notice that while we can get more accurate results in this case byreducing x, if we reduce it by a factor of 10 we must reduce t by a factor of100 to compensate, making the computation take 1000 times as long and use1000 times the memory!The Case of Variable ConductivityEarlier we mentioned that the problem we solved numerically could also besolved analytically. The value of the numerical method is that it can beapplied to similar partial differential equations for which an exact solutionis not possible or at least not known. For example, consider theone-dimensional heat equation with a variable coefficient, representing aninhomogeneous material with varying thermal conductivity k(x),∂u∂t=∂∂xk(x)∂u∂x= k(x)∂2u∂x2+ k (x)∂u∂x.For the first derivatives on the right-hand side, we use a symmetric finitedifference approximation, so that our discrete approximation to the partialdifferential equations becomesun+1j − unjt= kjunj+1 − 2unj + unj−1x2+kj+1 − kj−12 xunj+1 − unj−12 x,where kj = k(a + j x). Then the time iteration for this method isun+1j = sj unj+1 + unj−1 + (1 − 2sj) unj + 0.25 (sj+1 − sj−1) unj+1 − unj−1 , 190 Chapter 9: Applicationswhere sj = kj t/( x)2. In the following M-file, which we called heatvc.m,we modify our previous M-file to incorporate this iteration.function u = heatvc(k, x, t, init, bdry)% Solve the 1D heat equation with variable coefficient k on% the rectangle described by vectors x and t with% u(x, t(1)) = init and Dirichletdt/dxˆ2;u = zeros(N,J);u(1,:) = init;for n = 1:N-1u(n+1, 2:J-1) = s(2:J-1).*(u(n, 3:J) + u(n, 1:J-2)) + ...(1 - 2*s(2:J-1)).*u(n,2:J-1) + ...0.25*(s(3:J) - s(1:J-2)).*(u(n, 3:J) - u(n, 1:J-2));u(n+1, 1) = bdry(1);u(n+1, J) = bdry(2);endNotice that k is now assumed to be a vector with the same length as x andthat as a result so is s. This in turn requires that we use vectorizedmultiplication in the main iteration, which we have now split into threelines.Let's use this M-file to solve the one-dimensional variable-coefficient heatequation with the same boundary and initial conditions as before, usingk(x) = 1 + (x/5)2. Since the maximum value of k is 2, we can use the samevalues of t and x as before.kvals = 1 + (xvals/5).ˆ2;uvals = heatvc(kvals, xvals, tvals, init, [15 25]);surf(xvals, tvals, uvals)xlabel x; ylabel t; zlabel u Numerical Solution of the Heat Equation 191−50501234152025xtuIn this case the limiting temperature distribution is not linear; it has asteeper temperature gradient in the middle, where the thermalconductivity is lower. Again one could find the exact form of this limitingdistribution, u(x, t) = 20(1 + (1/π)arctan(x/5)), by setting the t derivativeto zero in the original equation and solving the resulting ordinarydifferential equation.You can use the method of finite differences to solve the heat equationin two or three space dimensions as well. For this and other partialdifferential equations with time and two space dimensions, you can alsouse the PDE Toolbox, which implements the more sophisticated finiteelement method.A SIMULINK SolutionWe can also solve the heat equation using SIMULINK. To do this wecontinue to approximate the x derivatives with finite differences, but wethink of the equation as a vector-valued ordinary differential equation, witht as the independent variable. SIMULINK solves the model using MATLAB'sODE solver, ode45. To illustrate how to do this, let's take the same examplewe started with, the case where k = 2 on the interval −5 ≤ x ≤ 5 from time 0to time 4, using boundary temperatures 15 and 25, and initial temperaturedistribution of 15 for x < 0 and 25 for x > 0. We replace u(x, t) for fixed t bythe vector u of values of u(x, t), with, say, x = -5:5. Here there are 11 192 Chapter 9: Applicationsvalues of x at which we are sampling u, but since u(x, t) is pre-determined atthe endpoints, we can take u to be a 9-dimensional vector, and we just tackon the values at the endpoints when we're done. Since we're replacing∂2u/∂x2by its finite difference approximation and we've taken x = 1 forsimplicity, our equation becomes the vector-valued ODE∂u∂t= k(Au + c).Here the right-hand side represents our approximation to k(∂2u/∂x2). Thematrix A isA =−2 1 · · · 01 −2............... 10 · · · 1 −2,since we are replacing ∂2u/∂x2at (n, t) with u(n − 1, t) − 2u(n, t) + u(n + 1, t).We represent this matrix in MATLAB's notation by-2*eye(9) + [zeros(8,1),eye(8);zeros(1,9)] +...[zeros(8,1),eye(8);zeros(1,9)]'The vector c comes from the boundary conditions, and has 15 in its firstentry, 25 in its last entry, and 0s in between. We represent it in MATLAB'snotation as [15;zeros(7,1);25] The formula for c comes from the factthat u(1) represents u(−4, t), and ∂2u/∂x2at this point is approximated byu(−5, t) − 2u(−4, t) + u(−3, t) = 15 − 2 u(1) + u(2),and similarly at the other endpoint. Here's a SIMULINK model representingthis equation:2k–C– boundaryconditionsScope1sIntegratorK*uGainNote that one needs to specify the initial conditions for u as BlockParameters for the Integrator block, and that in the Block Parameters dialog Numerical Solution of the Heat Equation 193box for the Gain block, one needs to set the multiplication type to "Matrix".Since u(1) through u(4) represent u(x, t) at x = −4 through −1, and u(6)through u(9) represent u(x, t) at x = 1 through 4, we take the initial valueof u to be [15*ones(4,1);20;25*ones(4,1)]. (The value 20 is acompromise at x = 0, since this is right in the middle of the regions where uis 15 and 25.) The output from the model is displayed in the Scope block inthe form of graphs of the various entries of u as functions of t, but it's moreuseful to save the output to the MATLAB Workspace and then plot it withsurf. To do this, go to the menu item Simulation Parameters... in theSimulation menu of the model. Under the Solver tab, set the stop time to4.0 (since we are only going out to t = 4), and under the Workspace I/O tab,check the "States" box under "Save to workspace", like this:After you run the model, you will find in your Workspace a 53 × 1 vectortout, plus a 53 × 9 matrix uout. Each row of these arrays corresponds to asingle time step, and each column of uout corresponds to one value of x. Butremember that we have to add in the values of u at the endpoints asadditional columns in u. So we plot the data as follows:u = [15*ones(length(tout),1), uout, 25*ones(length(tout),1)];x = -5:5;surf(x, tout, u)xlabel('x'), ylabel('t'), zlabel('u')title('solution to heat equation in a rod') 194 Chapter 9: Applications−50505101520152025xsolution to heat equation in a rodtuNote how similar this is to the picture obtained before. We leave it to thereader to modify the model for the case of variable heat conductivity.Solution with pdepeA new feature of MATLAB 6.0 is a built-in solver for partial differentialequations in one space dimension (as well as time t). To find out more aboutit, read the online help on pdepe. The instructions for use of pdepe are quiteexplicit but somewhat complicated. The method it uses is somewhat similarto that used in the SIMULINK solution above; that is, it uses an ODE solverin t and finite differences in x. The following M-file solves the secondproblem above, the one with variable conductivity. Note the use of functionhandles and subfunctions.function heateqex2% Solves a sample Dirichlet problem for the heat equation in a% rod, this time with variable conductivity, 21 mesh pointsm = 0; %This simply means geometry is linear.x = linspace(-5,5,21);t = linspace(0,4,81);sol = pdepe(m,@pdex,@pdexic,@pdexbc,x,t);% Extract the first solution component as u.u = sol(:,:,1);% A surface plot is often a good way to study a solution. 196 Chapter 9: Applications–5 –4 –3 –2 –1 0 1 2 3 4 51516171819202122232425Solution at t = 4xu(x,4)Again the results are very similar to those obtained before.A Model of Traffic FlowEveryone has had the experience of sitting in a traffic jam, or of seeing carsbunch up on a road for no apparent good reason. MATLAB and SIMULINKare good tools for studying models of such behavior. Our analysis here will bebased on "follow-the-leader" theories of traffic flow, about which you can readmore in Kinetic Theory of Vehicular Traffic, by Ilya Prigogine and RobertHerman, Elsevier, New York, 1971 or in The Theory of Road Traffic Flow, byWinifred Ashton, Methuen, London, 1966. We will analyze here an extremelysimple model that already exhibits quite complicated behavior. We consider aone-lane, one-way, circular road with a number of cars on it (a very primitivemodel of, say, the Inner Loop of the Capital Beltway around Washington, DC,since in very dense traffic, it is hard to change lanes and each lane behaveslike a one-lane road). Each driver slows down or speeds up on the basis of hisor her own speed, the speed of the car directly ahead, and the distance to thecar ahead. But human drivers have a finite reaction time. In other words, ittakes them a certain amount of time (usually about a second) to observewhat is going on around them and to press the gas pedal or the brake, asappropriate. The standard "follow-the-leader" theory supposes that¨un(t + T) = λ( ˙un−1(t) − ˙un(t)), (∗)where t is time; T is the reaction time; un is the position of the nth car; and A Model of Traffic Flow 197the "sensitivity coefficient" λ may depend on un−1(t) − un(t), the spacingbetween cars, and/or ˙un(t), the speed of the nth car. The idea behind thisequation is this. Drivers will tend to decelerate if they are going faster thanthe car in front of them, or if they are close to the car in front of them, andwill tend to accelerate if they are going slower than the car in front of them.In addition, drivers (especially in light traffic) may tend to speed up or slowdown depending on whether they are going slower or faster (respectively)than a "reasonable" speed for the road (often, but not always, equal to theposted speed limit). Since our road is circular, in this equation u0 isinterpreted as uN, where N is the total number of cars.The simplest version of the model is the one where the "sensitivitycoefficient" λ is a (positive) constant. Then we have a homogeneous lineardifferential-difference equation with constant coefficients for the velocities˙un(t). Obviously there is a "steady state" solution when all the velocities areequal and constant (i.e., traffic is flowing at a uniform speed), but what weare interested in is the stability of the flow, or the question of what effect isproduced by small differences in the velocities of the cars. The solution of (*)will be a superposition of exponential solutions of the form ˙un(t) = exp(αt)vn,where the vns and α are (complex) constants, and the system will beunstable if the velocities are unbounded; that is, there are any solutionswhere the real part of α is positive. Using vector notation, we have˙u(t) = exp(α t)v, ¨u(t + T) = α exp(α T) exp(α t)v.Substituting back in (*), we get the equationα exp(α T) exp(α t)v = λ(S− I) exp(α t)v,whereS =0 · · · 0 11 0 · · · 00 1 · · · ·· · · · · ·· · · 1 0 ·· · · 0 1 0is the "shift" matrix that, when it multiplies a vector on the left, cyclicallypermutes the entries of the vector. We can cancel the exp(α t) on each side togetα exp(α T)v = λ(S− I)v, or {S− [1 + (α/λ) exp(α T )]I }v = 0, (∗∗) 198 Chapter 9: Applicationswhich says that v is an eigenvector for S with eigenvalue 1 + (α/λ)eαT. Sincethe eigenvalues of S are the Nth roots of unity, which are evenly spacedaround the unit circle in the complex plane, and closely spaced together forlarge N, there is potential instability whenever 1 + (α/λ)eαThas absolutevalue 1 for some α with positive real part: that is, whenever (αT/λT)eαTcanbe of the form eiθ− 1 for some αT with positive real part. Whether instabilityoccurs or not depends on the value of the product λT. We can see this byplotting values of zexp(z) for z = αT = iy a complex number on the criticalline Re z = 0, and comparing with plots of λT(eiθ− 1) for various values ofthe parameter λT.syms y; expand(i*y*(cos(y) + i*sin(y)))ans =i*y*cos(y)-y*sin(y)ezplot(-y*sin(y), y*cos(y), [-2*pi, 2*pi]); hold ontheta = 0:0.05*pi:2*pi;plot((1/2)*(cos(theta) - 1), (1/2)*sin(theta), '-');plot(cos(theta) - 1, sin(theta), ':')plot(2*(cos(theta) - 1), 2*sin(theta), '--');title('iyeˆ{iy} and circles lambda T(eˆ{itheta}-1)');hold off–6 –4 –2 0 2 4 6 8–6–4–20246xyiyeiyand circles λ T(eiθ–1) A Model of Traffic Flow 199Here the small solid circle corresponds to λT = 1/2, and we are just at thelimit of stability, since this circle does not cross the spiral produced byzexp(z) for z a complex number on the critical line Re z = 0, though it "hugs"the spiral closely. The dotted and dashed circles, corresponding to λT = 1 or2, do cross the spiral, so they correspond to unstable traffic flow.We can check these theoretical predictions with a simulation usingSIMULINK. We'll give a picture of the SIMULINK model and thenexplain it..8sensitivityparameterrelativecar positions–C–initial velocities–C–initial car positionscar speedscarpositionsTo WorkspaceIn1 Out1Subsystem:computes velocitydifferencesReaction–timeDelayRamp1sxoIntegrateu to get u1sxoIntegrateu" to get u555555555 55555555Here the subsystem, which corresponds to multiplication by S− I, looks likethis:1Out1em1In144555555Here are some words of explanation. First, we are showing the model usingthe options Wide nonscalar lines and Signal dimensions in the Format 200 Chapter 9: Applicationsmenu of the SIMULINK model, to distinguish quantities that are vectorsfrom those that are scalars. The dimension 5 on most of the lines isthe value of N, the number of cars. Most of the model is like the example inChapter 8, except that our unknown function (called u), representing the carpositions, is vector-valued and not scalar-valued. The major exceptions arethese:1. We need to incorporate the reaction-time delay, so we've inserted aTransport Delay block from the Continuous block library.2. The parameter λ shows up as the value of the gain in the sensitivityparameter Gain block in the upper right.3. Plotting car positions by themselves is not terribly useful, since only therelative positions matter. So before outputting the car positions to theScope block labeled "relative car positions," we've subtracted off aconstant linear function (corresponding to uniform motion at theaverage car speed) created by the Ramp block from the Sources blocklibrary.4. We've made use of the option in the Integrator blocks to input the initialconditions, instead of having them built into the block. This makes thelogical structure a little clearer.5. We've used the subsystem feature of SIMULINK. If you enclose a bunch ofblocks with the mouse and then click on "Create subsystem" in themodel's Edit menu, SIMULINK will package them as a subsystem. Thisis helpful if your model is large or if there is some combination of blocksthat you expect to use more than once. Our subsystem sends a vector v to(S− I)v = Sv − v. A Sum block (with one of the signs changed to a −) isused for vector subtraction. To model the action of S, we've used theDemux and Mux blocks from the Signals and Systems block library. TheDemux block, with "number of outputs" parameter set to [4, 1], splits afive-dimensional vector into a pair consisting of a four-dimensional vectorand a scalar (corresponding to the last car). Then we reverse the orderand put them back together with the Mux block, with "number of inputs"parameter set to [1, 4].Once the model is assembled, it can be run with various inputs. Thefollowing pictures show the two scope windows with a set of conditionscorresponding to stable flow (though, to be honest, we've let two cars crossthrough each other briefly!): A Model of Traffic Flow 201As you can see, the speeds fluctuate but eventually converge to a singlevalue, and the separations between cars eventually stabilize.In contrast, if λ is increased by changing the "sensitivity parameter" in theGain block in the upper right, say from 0.8 to 2.0, one gets this sort of output,typical of instability: 202 Chapter 9: ApplicationsWe encourage you to go back and tinker with the model (for instance usinga sensitivity parameter that is also inversely proportional to the spacingbetween cars) and study the results. We should mention that the ToWorkspace block in the lower right has been put in to make it possible tocreate a movie of the moving cars. This block sends the car positions to avariable called carpositions. This variable is what is called a structurearray. To make use of it, you can create a movie with the following scriptM-file:theta = 0:0.025*pi:2*pi;for j = 1:length(tout)plot(cos(carpositions.signals.values(j, :)*2*pi), ...sin(carpositions.signals.values(j, :)*2*pi), 'o');axis([-1, 1, -1, 1]);hold on; plot(cos(theta), sin(theta), 'r'); hold off;axis equal;M(j) = getframe;endThe idea here is that we have taken the circular road to have radius 1 (insuitable units), so that the command plot(cos(theta),sin(theta),'r')draws a red circle (representing the road) in each frame of the movie, and ontop of that the cars are shown with moving little circles. The vector tout is alist of all the values of t at which the model computes the values of the vector A Model of Traffic Flow 203u(t), and at the jth time, the car positions are stored in the jth row of thematrix carpositions.signals.values. Try the program!We should mention here one fine point needed to create a realistic movie.Namely, we need the values of tout to be equally spaced — otherwise thecars will appear to be moving faster when the time steps are large and willappear to be moving slower when the time steps are small. In its defaultmode of operation, SIMULINK uses a variable-step differential equationsolver based on MATLAB's command ode45, and so the entries of tout willnot be equally spaced. To fix this, open the Simulation Parameters...dialog box using the Edit menu in the model window, choose the Solver tab,and change the Output options box to read: Produce specified outputonly, chosen to be something such as [0:0.5:20]. Then the model will outputthe car positions only at multiples of t = 0.5, and the MATLAB programabove will produce a 41-frame movie. Practice Set CDeveloping YourMATLAB SkillsRemarks. Problem 7 is a bit more advanced than the others. Problem 11arequires the Symbolic Math Toolbox; the others do not. SIMULINK is neededfor Problems 12 and 13.1. Captain Picard is hiding in a square arena, 50 meters on a side, which isprotected by a level-5 force field. Unfortunately, the Cardassians, who arefiring on the arena, have a death ray that can penetrate the force field.The point of impact of the death ray is exposed to 10,000 illumatons oflethal radiation. It requires only 50 illumatons to dispatch the Captain;anything less has no effect. The amount of illumatons that arrive at point(x, y) when the death ray strikes one meter above ground at point (x0, y0)is governed by an inverse square law, namely10,0004π((x − x0)2 + (y − y0)2 + 1).The Cardassian sensors cannot locate Picard's exact position, so they fireat a random point in the arena.(a) Use contour to display the arena after five random bursts of thedeath ray. The half-life of the radiation is very short, so one canassume it disappears almost immediately; only its initial burst hasany effect. Nevertheless include all five bursts in your picture, likea time-lapse photo. Where in the arena do you think Captain Picardshould hide?(b) Suppose Picard stands in the center of the arena. Moreover, supposethe Cardassians fire the death ray 100 times, each shot landing ata random point in the arena. Is Picard killed?(c) Rerun the "experiment" in part (b) 100 times, and approximate theprobability that Captain Picard can survive an attack of 100 shots.204 Practice Set C: Developing Your MATLAB Skills 205(d) Redo part (c) but place the Captain halfway to one side (that is,at x = 37.5, y = 25 if the coordinates of the arena are 0 ≤ x ≤ 50,0 ≤ y ≤ 50).(e) Redo the simulation with the Captain completely to one side, andfinally in a corner. What self-evident fact is reinforced for you?2. Consider an account that has M dollars in it and pays monthly interest J.Suppose beginning at a certain point an amount S is deposited monthlyand no withdrawals are made.(a) Assume first that S = 0. Using the Mortgage Payments application inChapter 9 as a model, derive an equation relating J, M, the numbern of months elapsed, and the total T in the account after n months.Assume that the interest is credited on the last day of the monthand that the total T is computed on the last day after the interestis credited.(b) Now assume that M = 0, that S is deposited on the first day of themonth, that as before interest is credited on the last day of themonth, and that the total T is computed on the last day after theinterest is credited. Once again, using the mortgage application asa model, derive an equation relating J, S, the number n of monthselapsed, and the total T in the account after n months.(c) By combining the last two models derive an equation relating all ofM, S, J, n, and T, now of course assuming there is an initial amountin the account (M) as well as a monthly deposit (S).(d) If the annual interest rate is 5%, and no monthly deposits are made,how many years does it take to double your initial stash of money?What if the annual interest rate is 10%?(e) In this and the next part, there is no initial stash. Assume an annualinterest rate of 8%. How much do you have to deposit monthly to bea millionaire in 35 years (a career)?(f) If the interest rate remains as in (e) and you can only afford todeposit $300 each month, how long do you have to work to retire amillionaire?(g) You hit the lottery and win $100,000. You have two choices: Takethe money, pay the taxes, and invest what's left; or receive $100,000/240 monthly for 20 years, depositing what's left after taxes. Assumea $100,000 windfall costs you $35,000 in federal and state taxes, butthat the smaller monthly payoff only causes a 20% tax liability. Inwhich way are you better off 20 years later? Assume a 5% annualinterest rate here.(h) Banks pay roughly 5%, the stock market returns 8% on average over 206 Practice Set C: Developing Your MATLAB Skillsa 10-year period. So parts (e) and (f) relate more to investing than tosaving. But suppose the market in a 5-year period returns 13%, 15%,−3%, 5%, and 10% in five successive years, and then repeats thecycle. (Note that the [arithmetic] average is 8%, though a geometricmean would be more relevant here.) Assume $50,000 is invested atthe start of a 5-year market period. How much does it grow to in5 years? Now recompute four more times, assuming you enter thecycle at the beginning of the second year, the third year, etc. Whichchoice yields the best/worst results? Can you explain why? Comparethe results with a bank account paying 8%. Assume simple annualinterest. Redo the five investment computations, assuming $10,000is invested at the start of each year. Again analyze the results.3. In the late 1990s, Tony Gwynn had a lifetime batting average of .339. Thismeans that for every 1000 at bats he had 339 hits. (For this exercise, weshall ignore walks, hit batsmen, sacrifices, and other plate appearancesthat do not result in an official at bat.) In an average year he amassed 500official at bats.(a) Design a Monte Carlo simulation of a year in Tony's career. Run it.What is his batting average?(b) Now simulate a 20-year career. Assume 500 official at bats everyyear. What is his best batting average in his career? What is hisworst? What is his lifetime average?(c) Now run the 20-year career simulation four more times. Answer thequestions in part (b) for each of the four simulations.(d) Compute the average of the five lifetime averages you computed inparts (b) and (c). What do you think would happen if you ran the20-year simulation 100 times and took the average of the lifetimeaverages for all 100 simulations?The next four problems illustrate some basic MATLAB programming skills.4. For a positive integer n, let A(n) be the n × n matrix with entries aij =1/(i + j − 1). For example,A(3) =1 1213121314131415 .The eigenvalues of A(n) are all real numbers. Write a script M-file thatprints the largest eigenvalue of A(500), without any extraneous output.(Hint: The M-file may take a while to run if you use a loop within a loopto define A. Try to avoid this!) Practice Set C: Developing Your MATLAB Skills 2075. Write a script M-file that draws a bulls-eye pattern with a central circlecolored red, surrounded by alternating circular strips (annuli) of whiteand black, say ten of each. Make sure the final display shows circles, notellipses. (Hint: One way to color the region between two circles black is tocolor the entire inside of the outer circle black and then color the inside ofthe inner circle white.)6. MATLAB has a function lcm that finds the least common multiple oftwo numbers. Write a function M-file mylcm.m that finds the least com-mon multiple of an arbitrary number of positive integers, which may begiven as separate arguments or in a vector. For example, mylcm(4, 5,6) and mylcm([4 5 6]) should both produce the answer 60. The pro-gram should produce a helpful error message if any of the inputs are notpositive integers. (Hint: For three numbers you could use lcm to find theleast common multiple mof the first two numbers and then use lcm againto find the least common multiple of m and the third number. Your M-filecan generalize this approach.)7. Write a function M-file that takes as input a string containing the nameof a text file and produces a histogram of the number of occurrences of eachletter from A to Z in the file. Try to label the figure and axes as usefully asyou can.8. Consider the following linear programming problem. Jane Doe is runningfor County Commissioner. She wants to personally canvass voters in thefour main cities in the county: Gotham, Metropolis, Oz, and River City.She needs to figure out how many residences (private homes, apartments,etc.) to visit in each city. The constraints are as follows:(i) She intends to leave a campaign pamphlet at each residence; sheonly has 50,000 available.(ii) The travel costs she incurs for each residence are: $0.50 in each ofGotham and Metropolis, $1 in Oz, and $2 in River City; she has$40,000 available.(iii) The number of minutes (on average) that her visits to each resi-dence require are: 2 minutes in Gotham, 3 minutes in Metropolis,1 minute in Oz, and 4 minutes in River City; she has 300 hoursavailable.(iv) Because of political profiles Jane knows that she should not visit anymore residences in Gotham than she does in Metropolis and thathowever many residences she visits in Metropolis and Oz, the totalof the two should not exceed the number she visits in River City;(v) Jane expects to receive, during her visits, on average, campaigncontributions of: one dollar from each residence in Gotham, a 208 Practice Set C: Developing Your MATLAB Skillsquarter from those in Metropolis, a half-dollar from the Oz resi-dents, and three bucks from the folks in River City. She must raiseat least $10,000 from her entire canvass.Jane's goal is to maximize the number of supporters (those likely tovote for her). She estimates that for each residence she visits in Gothamthe odds are 0.6 that she picks up a supporter, and the correspondingprobabilities in Metropolis, Oz, and River City are, respectively, 0.6, 0.5,and 0.3.(a) How many residences should she visit in each of the four cities?(b) Suppose she can double the time she can allot to visits. Now whatis the profile for visits?(c) But suppose that the extra time (in part (b)) also mandates that shedouble the contributions she receives. What is the profile now?9. Consider the following linear programming problem. The famous footballcoach Nerv Turnip is trying to decide how many hours to spend with eachcomponent of his offensive unit during the coming week — that is, thequarterback, the running backs, the receivers, and the linemen. The con-straints are as follows:(i) The number of hours available to Nerv during the week is 50.(ii) Nerv figures he needs 20 points to win the next game. He estimatesthat for each hour he spends with the quarterback, he can expecta point return of 0.5. The corresponding numbers for the runningbacks, receivers, and linemen are 0.3, 0.4, and 0.1, respectively.(iii) In spite of their enormous size, the players have a relatively thinskin. Each hour with the quarterback is likely to require Nerv tocriticize him once. The corresponding number of criticisms per hourfor the other three groups are 2 for running backs, 3 for receivers,and 0.5 for linemen. Nerv figures he can only bleat out 75 criticismsin a week before he loses control.(iv) Finally, the players are prima donnas who engage in rivalries. Be-cause of that, he must spend the exact same number of hours withthe running backs as he does with the receivers, at least as manyhours with the quarterback as he does with the runners and re-ceivers combined, and at least as many hours with the receivers aswith the linemen.Nerv figures he's going to be fired at the end of the season regardlessof the outcome of the game, so his goal is to maximize his pleasure duringthe week. (The team's owner should only know.) He estimates that, on asliding scale from 0 to 1, he gets 0.2 units of personal satisfaction for each Practice Set C: Developing Your MATLAB Skills 209diodebatteryresistorRiV0Figure C-1: A Nonlinear Electrical Circuithour with the quarterback. The corresponding numbers for the runners,receivers and linemen are 0.4, 0.3, and 0.6, respectively.(a) How many hours should Nerv spend with each group?(b) Suppose he only needs 15 points to win; then how many?(c) Finally suppose, despite needing only 15 points, that the troops aregetting restless and he can only dish out 70 criticisms this week. IsNerv getting the most out of his week?10. This problem, suggested to us by our colleague Tom Antonsen, concernsan electrical circuit, one of whose components does not behave linearly.Consider the circuit in Figure C-1.Unlike the resistor, the diode is a nonlinear element — it does not obeyOhm's Law. In fact its behavior is specified by the formulai = I0 exp(VD/VT), (1)where i is the current in the diode (which is the same as in the resistor byKirchhoff's Current Law), VD is the voltage across the diode, I0 is the leak-age current of the diode, and VT = kT/e, where k is Boltzmann's constant,T is the temperature of the diode, and e is the electrical charge.By Ohm's Law applied to the resistor, we also know that VR = iR,where VR is the voltage across the resistor and R is its resistance. But byKirchhoff's Voltage Law, we also have VR = V0 − VD. This gives a second 210 Practice Set C: Developing Your MATLAB Skillsequation relating the diode current and voltage, namelyi = (V0 − VD)/R. (2)Note now that (2) says that i is a decreasing linear function of VD with valueV0/R when VD is zero. At the same time (1) says that i is an exponentiallygrowing function of VD starting out at I0. Since typically, RI0 < V0, the tworesulting curves (for i as a function of VD) must cross once. Eliminating ifrom the two equations, we see that the voltage in the diode must satisfythe transcendental equation(V0 − VD)/R = I0 exp(VD/VT),orVD = V0 − RI0 exp(VD/VT).(a) Reasonable values for the electrical constants are: V0 = 1.5 volts,R = 1000 ohms, I0 = 10−5amperes, and VT = .0025 volts. Use fzeroto find the voltage VD and current i in the circuit.(b) In the remainder of the problem, we assume the voltage in the bat-tery V0 and the resistance of the resistor R are unchanged. Butsuppose we have some freedom to alter the electrical characteristicsof the diode. For example, suppose that I0 is halved. What happensto the voltage?(c) Suppose instead of halving I0, we halve VT. Then what is the effecton VD?(d) Suppose both I0 and VT are cut in half. What then?(e) Finally, we want to examine the behavior of the voltage if both I0 andVT are decreased toward zero. For definitiveness, assume that we setI0 = 10−5uand VT = .0025u, and let u → 0. Specifically, compute thesolution for u = 10− j, j = 0, . . . , 5. Then, display a loglog plot ofthe solution values, for the voltage as a function of I0. What do youconclude?11. This problem is based on both the Population Dynamics and 360˚ Pendu-lum applications from Chapter 9. The growth of a species was modeled inthe former by a difference equation. In this problem we will model pop-ulation growth by a differential equation, akin to the second applicationmentioned above. In fact we can give a differential equation model for thelogistic growth of a population x as a function of time t by the equation˙x = x(1 − x) = x − x2, (3) Practice Set C: Developing Your MATLAB Skills 211where ˙x denotes the derivative of x with respect to t. We think of x asa fraction of some maximal possible population. One advantage of thiscontinuous model over the discrete model in Chapter 9 is that we can geta "reading" of the population at any point in time (not just on integerintervals).(a) The differential equation (3) is solved in any beginning course inordinary differential equations, but you can do it easily with theMATLAB command dsolve. (Look up the syntax via online help.)(b) Now find the solution assuming an initial value x0 = x(0) of x. Usethe values x0 = 0, 0.25, . . . , 2.0. Graph the solutions and use yourpicture to justify the statement: "Regardless of x0 > 0, the solutionof (3) tends to the constant solution x(t) ≡ 1 in the long term."The logistic model presumes two underlying features of populationgrowth: (i) that ideally the population expands at a rate proportionalto its current total (that is, exponential growth — this correspondsto the x term on the right side of (3)) and (ii) because of interactionsbetween members of the species and natural limits to growth, unfet-tered exponential growth is held in check by the logistic term, givenby the −x2expression in (3). Now assume there are two speciesx(t) and y(t), competing for the same resources to survive. Thenthere will be another negative term in the differential equation thatreflects the interaction between the species. The usual model pre-sumes it to be proportional to the product of the two populations,and the larger the constant of proportionality, the more severe theinteraction, as well as the resulting check on population growth.(c) Here is a typical pair of differential equations that model the growthin population of two competing species x(t) and y(t):˙x(t) = x − x2− 0.5xy(4)˙y(t) = y − y2− 0.5xy.The command dsolve can solve many pairs of ordinary differentialequations — especially linear ones. But the mixture of quadraticterms in (4) makes it unsolvable symbolically, and so we need to use anumerical ODE solver as we did in the pendulum application. Usingthe commands in that application as a template, graph numerical 212 Practice Set C: Developing Your MATLAB Skillssolution curves to the system (4) for initial datax(0) = 0 : 1/12 : 13/12y(0) = 0 : 1/12 : 13/12.(Hint: Use axis to limit your view to the square 0 ≤ x, y ≤ 13/12.)(d) The picture you drew is called a phase portrait of the system. In-terpret it. Explain the long-term behavior of any population distri-bution that starts with only one species present. Relate it to part(b). What happens in the long term if both populations are presentinitially? Is there an initial population distribution that remainsundisturbed? What is it? Relate those numbers to the model (4).(e) Now replace 0.5 in the model by 2; that is, consider the new model˙x(t) = x − x2− 2xy(5)˙y(t) = y − y2− 2xy.Draw the phase portrait. (Use the same initial data and viewingsquare.) Answer the same questions as in part (d). Do you see aspecial solution trajectory that emanates from near the origin andproceeds to the special fixed point? And another trajectory from theupper right to the fixed point? What happens to all population dis-tributions that do not start on these trajectories?(f) Explain why model (4) is called "peaceful coexistence" and model (5)is called "doomsday." Now explain heuristically why the coefficientchange from 0.5 to 2 converts coexistence into doomsday.12. Build a SIMULINK model corresponding to the pendulum equation¨x(t) = −0.5˙x(t) − 9.81 sin(x(t)) (6)from The 360˚ Pendulum in Chapter 9. You will need the TrigonometricFunction block from the Math library. Use your model to redraw some ofthe phase portraits.13. As you know, Galileo and Newton discovered that all bodies near theearth's surface fall with the same acceleration g due to gravity, approx-imately 32.2 ft/sec2. However, real bodies are also subjected to forces dueto air resistance. If we take both gravity and air resistance into account,a moving ball can be modeled by the differential equation¨x = [0, −g] − c ˙x ˙x. (7)Here x, a function of the time t, is the vector giving the position of the ball(the first coordinate is measured horizontally, the second one vertically),˙x is the velocity vector of the ball, ¨x is the acceleration of the ball, ˙x Practice Set C: Developing Your MATLAB Skills 213is the magnitude of the velocity, that is, the speed, and c is a constantdepending on the shape and mass of the ball and the density of the air.(We are neglecting the lift force that comes from the ball's rotation, whichcan also play a major role in some situations, for instance in analyzingthe path of a curve ball, as well as forces due to wind currents.) For abaseball, the constant c turns out to be approximately 0.0017, assumingdistances are measured in feet and time is measured in seconds. (See,for example, Chapter 18, "Balls and Strikes and Home Runs," in TowingIcebergs, Falling Dominoes, and Other Adventures in Applied Mathematics,by Robert Banks, Princeton University Press, 1998.) Build a SIMULINKmodel corresponding to Equation (7), and use it to study the trajectory ofa batted baseball. Here are a few hints. Represent ¨x, ˙x, and x as vectorsignals, joined by two Integrator blocks. The quantity ¨x, according to (7),should be computed from a Sum block with two vector inputs. One shouldbe a Constant block with the vector value [0, −32.2], representing gravity,and the other should represent the drag term on the right of Equation(7), computed from the value of ˙x. You should be able to change one of theparameters to study what happens both with and without air resistance(the cases of c = 0.0017 and c = 0, respectively). Attach the output to anXY Graph block, with the parameters x-min = 0, y-min = 0, x-max = 500,y-max = 150, so that you can see the path of the ball out to a distance of500 feet from home plate and up to a height of 150 feet.(a) Let x(0) = [0, 4], ˙x(0) = [80, 80]. (This corresponds to the ball start-ing at t = 0 from home plate, 4 feet off the ground, with the hori-zontal and vertical components of its velocity both equal to 80 ft/sec.This corresponds to a speed off the bat of about 77 mph, which is notunrealistic.) How far (approximately — you can read this off yourXY Graph output) will the ball travel before it hits the ground, bothwith and without air resistance? About how long will it take the ballto hit the ground, and how fast will the ball be traveling at that time(again, both with and without air resistance)? (The last parts of thequestion are relevant for outfielders.)(b) Suppose a game is played in Denver, Colorado, where because ofthinning of the atmosphere due to the high altitude, c is only 0.0014.How far will the ball travel now (given the same initial velocity asin (a))?(c) (This is not a MATLAB problem.) Estimate from a comparison ofyour answers to (a) and (b) what effect altitude might have on theteam batting average of the Colorado Rockies. Chapter 10MATLAB and theInternetIn this chapter, we discuss a number of interrelated subjects: how to use theInternet to get additional help with MATLAB and to find MATLAB programsfor certain specific applications, how to disseminate MATLAB programs overthe Internet, and how to use MATLAB to prepare documents for posting onthe World Wide Web.MATLAB Help on the InternetFor answers to a variety of questions about MATLAB, it pays to visit the website for The MathWorks, MATLAB 6, the Web menu on the Desktop menu bar can take you thereautomatically.) Since files on this site are moved around periodically, we won'ttell you precisely what is located where, but we will point out a few thingsto look for. First, you can find complete documentation sets for MATLAB andall the toolboxes. This is particularly useful if you didn't install all the docu-mentation locally in order to save space. Second, there are lists of frequentlyasked questions about MATLAB, bug reports and bug fixes, etc. Third, there isan index of MATLAB-based books (including this one), with descriptions andordering information. And finally, there are libraries of M-files, developed bothby The MathWorks and by various MATLAB users, which you can downloadfor free. These are especially useful if you need to do a standard sort of calcu-lation for which there are established algorithms but for which MATLAB hasno built-in M-file; in all probability, someone has written an M-file for it andmade it available. You can also find M-files and MATLAB help elsewhere onthe Internet; a search on "MATLAB" will turn up dozens of MATLAB tutorials214 Posting MATLAB Programs and Output 215and help pages at all levels, many based at various universities. One of theseis the web site associated with this book, you can find nearly all of the MATLAB code used in this book.Posting MATLAB Programs and OutputTo post your own MATLAB programs or output on the Web, you have a numberof options, each with different advantages and disadvantages.M-Files, M-Books, Reports, and HTML FilesFirst, since M-files (either script M-files or function M-files) are simply plaintext files, you can post them, as is, on a web site, for interested parties to down-load. This is the simplest option, and if you've written a MATLAB programthat you'd like to share with the world, this is the way to do it. It's more likely,however, that you want to incorporate MATLAB graphics into a web page. Ifthis is the case, there are basically three options:1. You can prepare your document as an M-book in Microsoft Word. Afterdebugging and executing your M-book, you have two options. You cansimply post the M-book on your web site, allowing viewers with a Wordinstallation to read it, and allowing viewers with both a Word and aMATLAB installation to execute it. Or you can click on File : Save As...,and when the dialog box appears, under "Save as type", select "Web Page(∗.htm, ∗.html)". This will store your entire document in HTML (HyperTextMarkup Language) format for posting on the web, and will automaticallyconvert all of the graphics to the correct format. Once your web documentis created, you can modify it with any HTML editor (including Word itself).2. If you've installed the MATLAB Report Generator, it can take yourMATLAB programs and convert them into an HTML report with embed-ded graphics.3. Finally, you can create your web document with your favorite HTML editorand add links to your MATLAB graphics. For this to work, you need to saveyour graphics in a convenient format. The simplest way to do this is toselect File : Export... in your figure window. Under "Save as type" in thedialog box that appears, you can for instance select "JPEG images (∗.jpg)",and the resulting JPEG file can be incorporated into the document with a 216 Chapter 10: MATLAB and the Internettag such as <img src=sphere.jpg>. If you are not happy with the sizeof the resulting image, you can modify it with any image editor. (Almostany PC these days comes with one; in UNIX you can use ImageMagickC,xvC, or many other programs.) If you are planning to modify the imagebefore posting it, it may be preferable to have MATLAB store the figure inTIFF format instead; that way no resolution is lost before you begin theediting process. If you are an advanced MATLAB user and you want to use MATLAB as anengine to power an interactive web site, then you might want to purchase theMATLAB Web Server, which is designed exactly for this purpose. You can seesamples of what it can do at Your Web BrowserIn this section, we explain how to configure the most popular Web browsersto display M-files in the M-file editor or to launch M-books automatically.Microsoft Internet ExplorerIf MATLAB and Word are installed on your Windows computer then InternetExplorer should automatically know how to open M-books. With M-files, itmay give you a choice of downloading the file or "opening" it; if you choose thelatter, it will appear in the M-file editor, a slightly stripped-down version ofthe Editor/Debugger.Netscape NavigatorThe situation with Netscape Navigator is slightly more complicated. If youclick on an M-file (with the .m extension), it will probably appear as a plain textfile. You can save the file and then open it if you wish with the M-file editor.On a PC (but not in UNIX) you can open the M-file editor without launch-ing MATLAB; look for it in the MATLAB group under Start : Programs,or else look for the executable file meditor.exe (in MATLAB 5.3 and ear-lier, Medit.exe). If you click on an M-book (with the .doc extension), yourbrowser will probably offer you a choice of opening it or saving it, unlessyou have preconfigured Netscape to open it without prompting. (Thisdepends also on your security settings.) What program Netscape uses to open Configuring Your Web Browser 217Figure 10-1: The Netscape Preferences Panel.a file is controlled by your Preferences. To make changes, select Edit : Prefer-ences in the Netscape menu bar, find the Navigator section, and look for the"Applications" subsection. You will see a panel that looks something likeFigure 10-1. (Its exact appearance depends on what version of Netscape youare using and your operating system.) Look for the "Microsoft Word Document"file type (with file extension .doc) and, if necessary, change the program usedto open such files. Typical choices would be Word or Wordpad in Windowsand StarOffice or PC File Viewer in UNIX. Choices other than Word willonly allow you to view, not to execute, M-books. Chapter 11TroubleshootingIn this chapter, we offer advice for dealing with some common problems thatyou may encounter. We also list and describe the most common mistakes thatMATLAB users make. Finally, we offer some simple but useful techniques fordebugging your M-files.Common ProblemsProblems manifest themselves in various ways: Totally unexpected or plainlywrong output appears; MATLAB produces an error message (or at least awarning); MATLAB refuses to process an input line; something that workedearlier stops working; or, worst of all, the computer freezes. Fortunately, theseproblems are often caused by several easily identifiable and correctable mis-takes. What follows is a description of some common problems, together witha presentation of likely causes, suggested solutions, and illustrative examples.We also refer to places in the book where related issues are discussed.Here is a list of the problems:r wrong or unexpected output,r syntax error,r spelling error,r error messages when plotting,r a previously saved M-file evaluates differently, andr computer won't respond.Wrong or Unexpected OutputThere are many possible causes for this problem, but they are likely to beamong the following:218 Common Problems 219CAUSE: Forgetting to clear or reset variables.SOLUTION: Clear or initialize variables before using them, especially in a long ses-sion. See Variables and Assignments in Chapter 2.CAUSE: Conflicting definitions.SOLUTION: Do not use the same name for two different functions or variables, andin particular, try not to overwrite the names of any of MATLAB's built-infunctions.You can accidentally mask one of MATLAB's built-in M-files either with yourown M-file of the same name or with a variable (including, perhaps, an inlinefunction). When unexpected output occurs and you think this might be thecause, it helps to use which to find out what M-file is actually being referenced.Here is perhaps an extreme example.EXAMPLE:>> plot = gcf;>> x = -2:0.1:2;>> plot(x, x.ˆ2)Warning: Subscript indices must be integer values.??? Index into matrix is negative or zero. See releasenotes on changes to logical indices.What's wrong, of course, is that plot has been masked by a variable with thesame name. You could detect this with>> which plotplot is a variable.If you type clear plot and execute the plot command again, the prob-lem will go away and you'll get a picture of the desired parabola. A moresubtle example could occur if you did this on purpose, not thinking you woulduse plot, and then called some other graphics script M-file that uses itindirectly.CAUSE: Not keeping track of ans.SOLUTION: Assign variable names to any output that you intend to use.If you decide at some point in a session that you wish to refer to prior outputthat was unnamed, then give the output a name, and execute the command 220 Chapter 11: Troubleshootingagain. (The UP-ARROW key or Command History window is useful for recallingthe command to edit it.) Do not rely on ans as it is likely to be overwrittenbefore you execute the command that references the prior output.CAUSE: Improper use of built-in functions.SOLUTION: Always use the names of built-in functions exactly as MATLAB specifiesthem; always enclose inputs in parentheses, not brackets and not braces;always list the inputs in the required order. See Managing Variables and Online Help in Chapter 2.CAUSE: Inattention to precedence of arithmetic operations.SOLUTION: Use parentheses liberally and correctly when entering arithmetic oralgebraic expressions.EXAMPLE:MATLAB, like any calculator, first exponentiates, then divides and multiplies,and finally adds and subtracts, unless a different order is specified by usingparentheses. So if you attempt to compute 52/3− 25/(2 ∗ 3) by typing>> 5ˆ2/3 - 25/2*3ans =-29.1667the answer MATLAB produces is not what you intended because 5 is raisedto the power 2 before the division by 3, and 25 is divided by 2 before themultiplication by 3. Here is the correct calculation:>> 5ˆ(2/3) - 25/(2*3)ans =-1.2426Syntax ErrorCAUSE: Mismatched parentheses, quote marks, braces, or brackets.SOLUTION: Look carefully at the input line to find a missing or an extra delimiter.MATLAB usually catches this kind of mistake. In addition, the MATLAB 6Desktop automatically highlights matching delimiters as you type andcolor-codes strings (expressions enclosed in single quotes) so that you can see Common Problems 221where they begin and end. In the Command Window of MATLAB 5 and earlierversions, however, you have to hunt for matching delimiters by hand.CAUSE: Wrong delimiters: Using parentheses in place of brackets, or vice versa, andso on.SOLUTION: Remember the basic rules about delimiters in MATLAB.Parentheses are used both for grouping arithmetic expressions and for enclo-sing inputs to a MATLAB command, an M-file, or an inline function. Theyare also used for referring to an entry in a matrix. Square brackets are usedfor defining vectors or matrices. Single quote marks are used for definingstrings.EXAMPLE:The following illustrates what can happen if you don't follow these rules:>> X = -1:.01:1;>> X[1]??? X[1]|Error: Missing operator, comma, or semicolon.>> A=(0,1,2)??? A=(0,1,2)|Error: Error: ")" expected, "," found.These examples are fairly straightforward to understand; in the first case,X(1) was intended, and in the second case, A=[0,1,2] was intended. Buthere's a trickier example:>> sin 3ans =0.6702Here there's no error message, but if one looks closely, one discovers thatMATLAB has printed out the sine of 51 radians, not of 3 radians!! The ex-planation is as follows: Any time a MATLAB command is followed by a spaceand then an argument to the command (as in the construct clear x), theargument is always interpreted as a string. Thus MATLAB has inter-preted 3 not as the number 3, but as the string '3'! And sure enough, onediscovers: 222 Chapter 11: Troubleshooting>> char(51)ans =3In other words, in MATLAB's encoding scheme, the string '3' is stored as thenumber 51, which is why sin 3 (or also sin('3')) produces as output thesine of 51 radians.Braces or curly brackets are used less often than either parentheses orsquare brackets and are usually not needed by beginners. Their main useis with cell arrays. One example to keep in mind is that if you want an M-fileto take a variable number of inputs or produce a variable number of outputs,then these are stored in the cell arrays varargin and varargout, and bracesare used to refer to the cells of these arrays. Similarly, case is sometimes usedwith braces in the middle of a switch construct. If you want to construct avector of strings, then it has to be done with braces, since brackets when ap-plied to strings are interpreted as concatenation.EXAMPLE:>> {'a', 'b'}ans ='a' 'b'>> ['a', 'b']ans =abCAUSE: Improper use of arithmetic symbols.SOLUTION: When you encounter a syntax error, review your input line carefully formistakes in typing.EXAMPLE:If the user, intending to compute 2 times −4, inadvertently switches thesymbols, the result is>> 2 - * 4??? 2 - * 4|Error: Expected a variable, function, or constant,found "*". Common Problems 223Here the vertical bar highlights the place where MATLAB believes the erroris located. In this case, the actual error is earlier in the input line.Spelling ErrorCAUSE: Using uppercase instead of lowercase letters in MATLAB commands, ormisspelling the command.SOLUTION: Fix the spelling.For example, the UNIX version of MATLAB does not recognize Fzero or FZERO(in spite of the convention that the help lines in MATLAB's M-files alwaysrefer to capitalized function names); the correct command is fzero.EXAMPLE:>> Fzero(inline('xˆ2 - 3'), 1)??? Undefined function or variable ,Fzero,.>> FZERO(inline('xˆ2 - 3'), 1)??? Undefined function or variable ,FZERO,.>> text = help('fzero'); text(1:38)ans =FZERO Scalar nonlinear zero finding.>> fzero(inline('xˆ2 - 3'), 1)ans =1.7321Error Messages When PlottingCAUSE: There are several possible explanations, but usually the problem is the wrongtype of input for the plotting command chosen.SOLUTION: Carefully follow the examples in the help lines of the plotting command,and pay attention to the error messages.EXAMPLE:>> [X,Y] = meshgrid(-1:.1:1, -1:.1:1);>> mesh(X, Y, sqrt(1 - X.ˆ2 - Y.ˆ2))??? Error using ==> surfaceX, Y, Z, and C cannot be complex. 224 Chapter 11: TroubleshootingError in ==> /usr/matlabr12/toolbox/matlab/graph3d/mesh.mOn line 68 ==> hh = surface(x,,FaceColor,,fc,,EdgeColor,,,flat,, ,FaceLighting,, ,none,, ,EdgeLighting,, ,flat,);0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 100.10.20.30.40.50.60.70.80.91Figure 11-1These error messages indicate that you have tried to plot the wrong kind ofobject, and that's why the figure window (Figure 11-1) is blank. What's wrongin this case is evident from the first error message. While you might thinkyou can plot the hemisphere z = 1 − x2 − y2 this way, there are points in thedomain −1 ≤ x, y ≤ 1 where 1 − x2− y2is negative and thus the square rootis imaginary. But mesh can't handle complex inputs; the coordinates need tobe real. One can get around this by redefining the function at the points whereit's not real, like this:>> [X,Y] = meshgrid(-1:.1:1, -1:.1:1);>> mesh(X, Y, sqrt(max(1 - X.ˆ2 - Y.ˆ2, 0)))The output is shown in Figure 11-2.A Previously Saved M-File Evaluates DifferentlyOne of the most frustrating problems you may encounter occurs when apreviously saved M-file, one that you are sure is in good shape, won't eval-uate or evaluates incorrectly, when opened in a new session. Common Problems 225-1-0.500.51-1-0.500.5100.20.40.60.81Figure 11-2CAUSE: Change in the sequence of evaluation, or failure to clear variables.CAUSE: Differences between the Professional and Student VersionsEXAMPLE:Some commands that work correctly in the Professional Version of MATLABmay not work in the Student Version. Here is an example from MATLABRelease 11:>> syms p t>> ezsurf(sin(p)*cos(t), sin(p)*sin(t), cos(p), ...[0, pi, 0, 2*pi]); axis equalThis correctly plots a sphere (using spherical coordinates) in the ProfessionalVersion, but in the Student Version you get strange error messages such as??? The ,maple, function is restricted in theStudent Edition.Error in ==> C:MATLAB SR11toolboxsymbolicmaplemex.dllError in ==> C:MATLAB SR11toolboxsymbolicmaple.mOn line 116 ==> [result,status] = maplemex(statement);Error in ==> C:MATLAB SR11toolboxsymbolic@symezsurf.m(symfind)On line 104 ==> vars = maple([ vars , minus , ,pi, ]); 226 Chapter 11: TroubleshootingError in ==> C:MATLAB SR11toolboxsymbolic@symezsurf.m(makeinline)On line 73 ==> vars = symfind(f);Error in ==> C:MATLAB SR11toolboxsymbolic@symezsurf.mOn line 60 ==> F = makeinline(f);since ezsurf in the Student Version is not equipped to accept symbolic inputs;it requires string inputs instead. You can easily fix this by typing>> ezsurf('sin(p)*cos(t)', 'sin(p)*sin(t)', 'cos(p)', ...[0, pi, 0, 2*pi]); axis equalor else by using char to convert symbolic expressions to strings.Computer Won't RespondCAUSE: MATLAB is caught in a very large calculation, or some other calamity hasoccurred that has caused it to fail to respond. Perhaps you are using an arraythat is too large for your computer memory to handle.SOLUTION: Abort the calculation with CTRL+C.If overuse of computer memory is the problem, try to redo your calculationusing smaller arrays, for example, by using fewer grid points in a 3D plot,or by breaking a large vectorized calculation into smaller pieces using a loop.Clearing large arrays from your Workspace may help too.EXAMPLE:You'll know it when you see it!The Most Common MistakesThe most common mistakes are all accounted for in the causes of the problemsdescribed earlier. But to help you prevent these mistakes, we compile themhere in a single list to which you can refer periodically. Doing so will help youto establish "good MATLAB habits". The most common mistakes arer forgetting to clear values,r improperly using built-in functions,r not paying attention to the order of precedence of arithmetic operations,r improperly using arithmetic symbols,r mismatching delimiters,r using the wrong delimiters, Debugging Techniques 227r plotting the wrong kind of object, andr using uppercase instead of lowercase letters in MATLAB commands, ormisspelling commands.Debugging TechniquesNow that we have discussed the most common mistakes, it's time to discusshow to debug your M-files, and how to locate and fix those pesky problemsthat don't fit into the neat categories above.If one of your M-files is not working the way you expected, perhaps theeasiest thing you can do to debug it is to insert the command keyboard some-where in the middle. This temporarily suspends (but does not stop) executionand returns command to the keyboard, where you are given a special promptwith a K in it. You can execute whatever commands you want at this point(for instance, to examine some of the variables). To return to execution of theM-file, type return or dbcont, short for "debug continue."A more systematic way to debug M-files is to use the MATLAB M-filedebugger to insert "breakpoints" in the file. Usually you would do this withthe Breakpoints menu or with the "Set/clear breakpoint" icon at the top ofthe Editor/Debugger window, but you can also do this from the command linewith the command dbstop. Once a breakpoint is inserted in the M-file, youwill see a little red dot next to the appropriate line in the Editor/Debugger. (Anexample is illustrated in Figure 11-8 below.) Then when you call the M-file,execution will stop at the breakpoint, and just as in the case of keyboard,control will return to the Command Window, where you will be given a specialprompt with a K in it. Again, when you are ready to resume execution of theM-file, type dbcont. When you are done with the debugging process, dbclear"clears" the breakpoint from the M-file.Let's illustrate these techniques with a real example. Suppose you wantto construct a function M-file that takes as input two expressions f and g(given either as symbolic expressions or as strings) and two numbers a and b,plots the functions f and g between x = a and x = b, and shades the region inbetween them. As a first try, you might start with the nine-line function M-fileshadecurves.m given as follows: 230 Chapter 11: TroubleshootingIt's not too hard to figure out why our regions aren't shaded; that's be-cause we used plot (which plots curves) instead of patch (which plots filledpatches). So that suggests we should try changing the last line of theM-file topatch([xvals, xvals], [ffun(xvals), gfun(xvals)])That gives the error message??? Error using ==> patchNot enough input arguments.Error in ==> shadecurves.mOn line 9 ==> patch([xvals, xvals], [ffun(xvals),gfun(xvals)])So we go back and try>> help patchto see if we can get the syntax right. The help lines indicate that patchrequires a third argument, the color (in RGB coordinates) with which ourpatch is to be filled. So we change our final line to, for instance,patch([xvals,xvals], [ffun(xvals),gfun(xvals)], [.2,0,.8])That gives us now as output to shadecurves(xˆ2, sqrt(x), 0, 1);axis square the picture shown in Figure 11-6.That's better, but still not quite right, because we can see a mysteriousdiagonal line down the middle. Not only that, but if we try>> syms x; shadecurves(xˆ2, xˆ4, -1.5, 1.5)we now get the bizarre picture shown in Figure 11-7.There aren't a lot of lines in the M-file, and lines 7 and 8 seem OK, sothe problem must be with the last line. We need to reread the online help forpatch. It indicates that patch draws a filled 2D polygon defined by the vectorsX and Y, which are its first two inputs. A way to see how this is working is tochange the "50" in line 9 of the M-file to something much smaller, say 5, andthen insert a breakpoint in the M-file before line 9. At this point, our M-filein the Editor/Debugger window now looks like Figure 11-8. Note the large dotto the left of the last line, indicating the breakpoint. When we run the M-filewith the same input, we now obtain in the Command Window a K>> prompt.At this point, it is logical to try to list the coordinates of the points that arethe vertices of our filled polygon, so we try 232 Chapter 11: TroubleshootingFigure 11-8: The Editor/Debugger.K>> [[xvals, xvals]', [ffun(xvals), gfun(xvals)]']ans =-1.5000 2.2500-0.9000 0.8100-0.3000 0.09000.3000 0.09000.9000 0.81001.5000 2.2500-1.5000 5.0625-0.9000 0.6561-0.3000 0.00810.3000 0.00810.9000 0.65611.5000 5.0625If we now typeK>> dbcontwe see in the figure window what is shown in Figure 11-9 below.Finally we can understand what is going on; MATLAB has "connected thedots" using the points whose coordinates were just printed out, in the or-der it encountered them. In particular, MATLAB has drawn a line from thepoint (1.5, 2.25) to the point (−1.5, 5.0625). This is not what we wanted; wewanted MATLAB to join the point (1.5, 2.25) on the curve y = x2to the point(1.5, 5.0625) on the curve y = x4. We can fix this by reversing the order of the Debugging Techniques 233-1. 5 -1 -0. 5 0 0.5 1 1.50123456Figure 11-9x coordinates at which we evaluate the second function g. So letting slavxdenote xvals reversed, we correct our M-file to read% Example: shadecurves('sin(x)', '-sin(x)', 0, pi)ffun = inline(vectorize(f)); gfun = inline(vectorize(g));xvals = a:(b - a)/50:b; slavx = b:(a - b)/50:a;patch([xvals,slavx], [ffun(xvals),gfun(slavx)], [.2,0,.8])Now it works properly. Sample output from this M-file is shown in Figure 11-4.Try it out on the other examples we have discussed, or on others of your choice. Practice Set A 243–2 –1.5 –1 –0.5 0 0.5 1 1.5 2–2024681012Problem 10Let's plot 2xand x4and look for points of intersection. We plot them firstwith ezplot just to get a feel for the graph.ezplot('xˆ4'); hold on; ezplot('2ˆx'); hold off−6 −4 −2 0 2 4 605101520253035404550x2xNote the large vertical range. We learn from the plot that there are no pointsof intersection between 2 and 6 or −6 and −2; but there are apparently twopoints of intersection between −2 and 2. Let's change to plot now and focuson the interval between −2 and 2. We'll plot the monomial dashed.X = -2:0.1:2; plot(X, 2.ˆX); hold on; plot(X, X.ˆ4, '--');hold off 244 Solutions to the Practice Sets−2 −1.5 −1 −0.5 0 0.5 1 1.5 20246810121416We see that there are points of intersection near −0.9 and 1.2. Are there anyother points of intersection? To the left of 0, 2xis always less than 1, whereasx4goes to infinity as x goes to −∞. However, both x4and 2xgo to infinity asx goes to ∞, so the graphs may cross again to the right of 6. Let's check.X = 6:0.1:20; plot(X, 2.ˆX); hold on; plot(X, X.ˆ4, '--');hold off6 8 10 12 14 16 18 20024681012x 105We see that they do cross again, near x = 16. If you know a little calculus,you can show that the graphs never cross again (by taking logarithms, forexample), so we have found all the points of intersection. Now let's usefzero to find these points of intersection numerically. This command looksfor a solution near a given starting point. To find the three different points of Practice Set C 2670 5 10 15 20 25 30 35 40 45 5005101520253035404550It is not so clear from the picture where to hide, although it looks like theCaptain has a pretty good chance of surviving a small number of shots.But 100 shots may be enough to find him. Intuition says he ought to stayclose to the boundary.(b)Below is a series of commands that places Picard at the center of thearena, fires the death ray 100 times, and then determines the health ofPicard. It uses the function lifeordeath, which computes the fate ofthe Captain after a single shot.function r = lifeordeath(x1, y1, x0, y0)%This file computes the number of illumatons.%that arrive at the point (x1, y1), assuming the death,%ray strikes 1 meter above the point (x0, y0).%If that number exceeds 50, a ''1" is returned in the%variable ''r"; otherwise a ''0" is returned for ''r".dosage = 10000/(4*pi*((x1 - x0)ˆ2 + (y1 - y0)ˆ2 + 1));if dosage > 50r = 1; Practice Set C 271They say a brave man dies but a single time, but a coward dies athousand deaths. But the person who said that probably neverencountered a Cardassian. Long live Picard!Problem 2(a)Consider the status of the account on the last day of each month. At theend of the first month, the account has M + M × J = M(1 + J ) dollars.Then at the end of the second month the account contains[M(1 + J )](1 + J ) = M(1 + J )2dollars. Similarly, at the end of n months,the account will hold M(1 + J )ndollars. Therefore, our formula isT = M(1 + J )n.(b)Now we take M = 0 and S dollars deposited monthly. At the end of thefirst month the account has S+ S× J = S(1 + J) dollars. S dollars areadded to that sum the next day, and then at the end of the second monththe account contains [S(1 + J ) + S](1 + J) = S[(1 + J)2+ (1 + J)]dollars. Similarly, at the end of n months, the account will holdS[(1 + J)n+ · · · + (1 + J)]dollars. We recognize the geometric series — with the constant term "1"missing, so the amount T in the account after n months will equalT = S[((1 + J)n+1− 1)/((1 + J) − 1) − 1] = S[((1 + J)n+1− 1)/J − 1].(c)By combining the two models it is clear that in an account with an initialbalance M and monthly deposits S, the amount of money T after nmonths is given byT = M (1 + J)n+ S[((1 + J)n+1− 1)/J − 1].(d)We are asked to solve the equation(1 + J)n= 2with the values J = 0.05/12 and J = 0.1/12. 274 Solutions to the Practice Sets3.00 72794.744.00 72794.745.00 72794.74The results are all the same; you wind up with $72,795 regardless ofwhere you enter in the cycle, because the product 1≤ j≤5(1 + rates( j))is independent of the order in which you place the factors. If you put the$50,000 in a bank account paying 8%, you get50000*(1.08)ˆ5ans =73466.40that is, $73,466 — better than the market. The market's volatility hurtsyou compared to the bank's stability. But of course that assumes you canfind a bank that will pay 8%. Now let's see what happens with no stash,but an annual investment instead. The analysis is more subtle here. SetS = 10, 000 (which now represents a yearly deposit). At the end of oneyear, the account contains S(1 + r1); then at the end of the second year(S(1 + r1) + S)(1 + r2), where we have written rj for rates( j). So at theend of 5 years, the amount in the account will be the product of S and thenumberj≥1(1 + rj) + j≥2(1 + rj) + j≥3(1 + rj) + j≥4(1 + rj) + (1 + r5).If you enter at a different year in the business cycle the terms get cycledappropriately. So now we can computeformat shortfor k = 0:4T = ones(1, 5);for j = 1:5TT = 1;for m = j:5TT = TT*(1 + rates(k + m));endT(j) = TT;end Practice Set C 275disp([k + 1, sum(T)])end1.0000 6.11962.0000 6.40003.0000 6.83584.0000 6.18855.0000 6.0192Multiplying each of these by $10,000 gives the portfolio amounts for thefive scenarios. Not surprisingly, all are less than what one obtains byinvesting the original $50,000 all at once. But in this model it matterswhere you enter the business cycle. It's clearly best to start yourinvestment program when a recession is in force and end in a boom.Incidentally, the bank model yields in this case(1/.08)*(((1.08)ˆ6) - 1) - 1ans =6.3359which is better than the results of some of the previous investment modelsand worse than others.Problem 3(a)First we define an expression that computes whether Tony gets a hit ornot during a single at bat, based on a random number chosen between 0and 1. If the random number is less than or equal to 0.339, Tony iscredited with a hit, whereas if the number exceeds 0.339, he is retired bythe opposition.Here is an M-file, called atbat.m, which computes the outcome of a singleat bat:%This file simulates a single at bat.%The variable r contains a ''1" if Tony gets a hit,%that is, if rand <= 0.339; and it contains a ''0"%if Tony fails to hit safely, that is, if rand > 0.339.s = rand; 276 Solutions to the Practice Setsif s <= 0.339r = 1;elser = 0;endWe can simulate a year in Tony's career by evaluating the script M-fileatbat 500 times. The following program does exactly that. Then itcomputes his average by adding up the number of hits and dividing bythe number of at bats, that is, 500. We build in a variable that allows fora varying number of at bats in a year, although we shall only use 500.function y = yearbattingaverage(n)%This function file computes Tony's batting average for%a single year, by simulating n at bats, adding up the%number of hits, and then dividing by n.X = zeros(1, n);for i = 1:natbat;X(i) = r;endy = sum(X)/n;yearbattingaverage(500)ans =0.3200(b)Now let's write a function M-file that simulates a 20-year career. As withthe number of at bats in a year, we'll allow for a varying length career.function y = career(n,k)%This function file computes the batting average for each%year in a k-year career, asuming n at bats in each year.%Then it lists the maximum, minimum, and lifetime average.Y = zeros(1, k);for j = 1:kY(j) = yearbattingaverage(n);end 278 Solutions to the Practice Sets(.3439 + .3393 + .3381 + .3428 + .3311)/5ans =0.33904000000000How about that!If we ran the simulation 100 times and took the average it would likelybe extremely close to .339 — even closer than the previous number.Problem 4Our solution and its output are below. First we set n to 500 to save typing inthe following lines and make it easier to change this value later. Then we setup a row vector j and a zero matrix A of the appropriate sizes and begin aloop that successively defines each row of the matrix. Notice that on the linedefining A(i,j), i is a scalar and j is a vector. Finally, we extract themaximum value from the list of eigenvalues of A.n = 500;j = 1:n;A = zeros(n);for i = 1:nA(i,j) = 1./(i + j - 1);endmax(eig(A))ans =2.3769Problem 5Again we display below our solution and its output. First we define a vectort of values between 0 and 2π, in order to later represent circlesparametrically as x = r cos t, y = r sin t. Then we clear any previous figurethat might exist and prepare to create the figure in several steps. Let's saythe red circle will have radius 1; then the first black ring should have innerradius 2 and outer radius 3, and thus the tenth black ring should have innerradius 20 and outer radius 21. We start drawing from the outside in because Practice Set C 279the idea is to fill the largest circle in black, then fill the next largest circle inwhite leaving only a ring of black, then fill the next largest circle in blackleaving a ring of white, etc. The if statement tests true when r is odd andfalse when it is even. We stop the alternation of black and white at a radiusof 2 to make the last circle red instead of black; then we adjust the axes tomake the circles appear round.t = linspace(0, 2*pi, 100);cla reset; hold onfor r = 21:-1:2if mod(r, 2)fill(r*cos(t), r*sin(t), 'k')elsefill(r*cos(t), r*sin(t), 'w')endendfill(cos(t), sin(t), 'r')axis equal; hold off−25 −20 −15 −10 −5 0 5 10 15 20 25−20−15−10−505101520Problem 6Here are the contents of our solution M-file:function m = mylcm(varargin)nums = [varargin{:}];if ~isnumeric(nums) any(nums ~= round(real(nums))) ...any(nums <= 0) Practice Set C 285Optimization terminated successfully.ans =18.66679.33339.33339.3333Nerv must spend 1823hours with the quarterback and 913hours witheach of the other three groups. Note that the total is less than 50, leavingNerv some free time to look for a job for next year.Problem 10syms V0 R I0 VT xf = x - V0 + R*I0*exp(x/VT)f =x-V0+R*I0*exp(x/VT)(a)VD = fzero(char(subs(f, [V0, R, I0, VT], [1.5, 1000, 10ˆ(-5),.0025])), [0, 1.5])VD =0.0125That's the voltage; the current is thereforeI = (1.5 - VD)/1000I =0.0015(b)g = subs(f, [V0, R], [1.5, 1000])g =x-3/2+1000*I0*exp(x/VT) 286 Solutions to the Practice Setsfzero(char(subs(g, [I0, VT], [(1/2)*10ˆ(-5), .0025])),[0, 1.5])ans =0.0142Not surprisingly, the voltage goes up slightly.(c)fzero(char(subs(g, [I0, VT], [10ˆ(-5), .0025/2])), [0, 1.5])??? Error using ==> fzeroFunction values at interval endpoints must be finite andreal.The problem is that the values of the exponential are too big at theright-hand endpoint of the test interval. We have to specify an intervalbig enough to catch the solution, but small enough to prevent theexponential from blowing up too drastically at the right endpoint. Thiswill be the case even more dramatically in part (e) below.fzero(char(subs(g, [I0, VT], [10ˆ(-5), .0025/2])), [0, 0.5])ans =0.0063This time the voltage goes down.(d)Next we halve both:fzero(char(subs(g, [I0, VT], [(1/2)*10ˆ(-5), .0025/2])), [0,0.5])ans =0.0071The voltage is less than in part (b) but more than in part (c).(e)syms uh = subs(g, [I0, VT], [10ˆ(-5)*u, 0.0025*u]) Practice Set C 289The graphical evidence suggests that: The solution that starts at zero staysthere; all the others tend toward the constant solution 1.(c)clear all; close all; hold onf = inline('[x(1) - x(1)ˆ2 - 0.5*x(1)*x(2); x(2) - x(2)ˆ2 -0.5(d)The endpoints on the curves are the start points. So clearly any curvethat starts out inside the first quadrant, that is, one that corresponds toa situation in which both populations are present at the outset, tendstoward a unique point — which from the graph appears to be about(2/3,2/3). In fact if x = y = 2/3, then the right sides of both equations in(4) vanish, so the derivatives are zero and the values of x(t) and y(t)remain constant — they don't depend on t. If only one species is presentat the outset, that is, you start out on one of the axes, then the solution 290 Solutions to the Practice Setstends toward either (1,0) or (0,1) depending on whether x or y is thespecies present. That is precisely the behavior we saw in part (b).(e)close all; hold onf = inline('[x(1) - x(1)ˆ2 - 2*x(1)*x(2); x(2) - x(2)ˆ2 -2This time most of the curves seem to be tending toward one of the points(1,0) or (0,1) — in particular, any solution curve that starts on one of theaxes (corresponding to no initial poulation for the other species) does so. Itseems that whichever species has a greater population at the outset willeventually take over all the population — the other will die out. But thereis a delicate balance in the middle — it appears that if the two populationsare about equal at the outset, then they tend to the unique populationdistribution at which, if you start there, nothing happens. That valuelooks like (1/3,1/3). In fact this is the value that renders both sides of (5)zero and its role is analogous to that played by (2/3,2/3) in part (d). Practice Set C 291(f)It makes sense to refer to the model (4) as "peaceful coexistence", sincewhatever initial populations you have — provided both are present —you wind up with equal populations eventually. "Doomsday" is anappropriate name for model (5), since if you start out with unequalpopulations, then the smaller group becomes extinct. The lowercoefficient 0.5 means relatively small interaction between the species,allowing for coexistence. The larger coefficient 2 means strongerinteraction and competition, precluding the survival of both.Problem 12Here is a SIMULINK model for redoing the pendulum application fromChapter 9:With the initial conditions x(0) = 0, ˙x(0) = 10, the XY Graph block shows thefollowing phase portrait: 292 Solutions to the Practice SetsMeanwhile, the Scope block gives the following graph of x as a function of t:Problem 13Here is a SIMULINK model for studying the equation of motion of a baseball: Practice Set C 293y vs. tmagnitudeof velocity[80,80]initialvelocityXY GraphsqrtMathFunction1sxoIntegratex'' to get x'1sIntegratex' to get xC GravityKGainDot ProductemComputeaccelerationdue to drag|x'|The way this works is fairly straightforward. The Integrator block in theupper left integrates the acceleration (a vector quantity) to get the velocity(also a vector — we have chosen the option, from the Format menu, ofindicating vector quantities with thicker arrows). This block requires theinitial value of the velocity as an initial condition; we define it in the "initialvelocity" Constant block. Output from the first Integrator goes into thesecond Integrator, which integrates the velocity to get the position (also avector). The initial condition for the position, [0, 4], is stored in theparameters of this second Integrator. The position vector is fed into a Demuxblock, which splits off the horizontal and vertical components of the position.These are fed into the XY Graph block, and also the vertical component is fedinto a scope block so that we can see the height of the ball as a function oftime. The hardest part is the computation of the acceleration:¨x = [0, −g] − c ˙x ˙x.This is computed by adding the two terms on the right with the Sum blocknear the lower left. The value of [0, −g] is stored in the "gravity" Constantblock. The second term on the right is computed in the Product block labeled"Compute acceleration due to drag", which multiplies the velocity (a vector)by −c times the speed (a scalar). We compute the speed by taking the dot 294 Solutions to the Practice Setsproduct of the velocity with itself and then taking the square root; then wemultiply by −c in the Gain block in the middle bottom of the model. TheScope block in the lower right plots the ball's speed as a function of time.(a)With c set to 0 (no air resistance) and the initial velocity set to [80, 80], theball follows a familiar parabolic trajectory, as seen in the following picture:Note that the ball travels about 400 feet before hitting the ground, and sothe trajectory is just about what is required for a home run in mostballparks. We can read off the flight time and final speed from the othertwo scopes: Practice Set C 295Thus the ball stays in the air about 5 seconds and is traveling about 115ft/sec when it hits the ground.Now let's see what happens when we factor in air resistance, again withthe initial velocity set to [80, 80]. First we take c = 0.0017. The trajectorynow looks like this:Note the enormous difference air resistance makes; the ball only travelsabout 270 feet. We can also investigate the flight time and speed with theother two scopes: 296 Solutions to the Practice SetsSo the ball is about 80 feet high at its peak, and hits the ground in about412seconds. Its final speed can be read off from the picture:So the final speed is only about 80 ft/sec, which is much gentler on thehands of the outfielder than in the no-air-resistance case.(b)Let's now redo exactly the same calculation with c = 0.0014(corresponding to playing in Denver). The ball's trajectory is now: Practice Set C 297The ball goes about 285 feet, or about 15 feet further than when playingat sea level. This particular ball is probably an easy play, but with somehard-hit balls, those extra 15 feet could mean the difference between anout and a home run. If we look at the height scope for the Denvercalculation, we see:So there is a very small increase in the flight time. Similarly, if we look atthe speed scope for the Denver calculation, we see: 298 Solutions to the Practice Setsand so the final speed is a bit faster, about 83 ft/sec.(c)One would expect that batting averages would be higher in Denver, asindeed is the case according to Major League Baseball statistics. GlossaryWe present here the most commonly used MATLAB objects in six categories:operators, built-in constants, built-in functions, commands, graphics com-mands, and MATLAB programming constructs. Though MATLAB doesnot distinguish between commands and functions, it is convenient to thinkof a MATLAB function as we normally think of mathematical functions. AMATLAB function is something that can be evaluated or plotted; a com-mand is something that manipulates data or expressions or that initiates aprocess.We list each operator, function, and command together with a shortdescription of its effect, followed by one or more examples. Many MATLABcommands can appear in a number of different forms, because you can applythem to different kinds of objects. In our examples, we have illustrated themost commonly used forms of the commands. Many commands also have nu-merous optional arguments; in this glossary, we have only included some verycommon options. You can find a full description of all forms of a command,and get a more complete accounting of all the optional arguments availablefor it, by reading the help text — which you can access either by typing help<commandname> or by invoking the Help Browser, shown in Figure G-1.This glossary does not contain a comprehensive list of MATLAB commands.We have selected the commands that we feel are most important. You can finda comprehensive list in the Help Browser. The Help Browser is accessiblefrom the Command Window by typing helpdesk or helpwin, or from theLaunch Pad window in your Desktop under MATLAB : Help. Exactly whatcommands are covered in your documentation depends on your installation, inparticular which toolboxes and what parts of the overall documentation filesyou installed. See Online Help in Chapter 2 for a detailed description of the Help Browser.299 300 GlossaryFigure G-1: The Help Browser, Opened to "Graphics".MATLAB Operators Left matrix division. X = AB is the solution of the equation A*X = B. Type helpslash for more information.A = [1 0; 2 1]; B = [3; 5];AB/ Ordinary scalar division, or right matrix division. For matrices, A/B is essentiallyequivalent to A*inv(B). Type help slash for more information.* Scalar or matrix multiplication. See the online help for mtimes.. Not a true MATLAB operator. Used in conjunction with arithmetic operators toforce element-by-element operations on arrays. Also used to access fields of a struc-ture array.a = [1 2 3]; b = [4 -6 8];a.*bsyms x y; solve(x + y - 2, x - y); ans.x.* Element-by-element multiplication of arrays. See the previous entry and theonline help for times.ˆ Scalar or matrix powers. See the online help for mpower..ˆ Element-by-element powers. See the online help for power. Glossary 301: Range operator, used for defining vectors and matrices. Type help colon for moreinformation.' Complex conjugate transpose of a matrix. See ctranspose. Also delimits thebeginning and end of a string.; Suppresses output of a MATLAB command, and can be used to separate commandson a command line. Also used to separate the rows of a matrix or column vector.X = 0:0.1:30;[1; 2; 3], Separates elements of a row of a matrix, or arguments to a command. Can also beused to separate commands on a command line..' Transpose of a matrix. See transpose.... Line continuation operator. Cannot be used inside quoted strings. Type helppunct for more information.1 + 3 + 5 + 7 + 9 + 11 ...+ 13 + 15 + 17['This is a way to create very long strings ', ...'that span more than one line. Note the square brackets.']! Run command from operating system.!C:Programsprogram.bat% Comment. MATLAB will ignore the rest of the same line.@ Creates a function handle.fminbnd(@cos, 0, 2*pi)Built-in Constantseps Roughly the size of the computer's floating point round-off error; on mostcomputers it is around 2 × 10−16.exp(1) e = 2.71828 . . . . Note that e has no special meaning.i i =√−1. This assignment can be overridden, for example, if you want to use i asan index in a for loop. In that case j can be used for the imaginary unit.Inf ∞. Also inf (in lower-case letters).NaN Not a number. Used for indeterminate expressions such as 0/0.pi π = 3.14159 . . . . 306 Glossarylength Returns the number of elements in a vector or string.length('abcde')limit Finds a two-sided limit, if it exists. Use 'right' or 'left' for one-sidedlimits.syms x; limit(sin(x)/x, x, 0)syms x; limit(1/x, x, Inf, 'left')linspace Generates a vector of linearly spaced points.linspace(0, 2*pi, 30)load Loads Workspace variables from a disk file.load filenamelookfor Searches for a specified string in the first line of all M-files found in theMATLAB path.lookfor odels Lists files in the current working directory. Similar to dir.maple String access to the Maple kernel; generally is used in the formmaple('function', 'arg'). Not available in the Student Version.maple('help', 'csgn')max Computes the arithmetic maximum of the entries of a vector.X = [3 5 1 -6 23 -56 100]; max(X)mean Computes the arithmetic average of the entries of a vector.X = [3 5 1 -6 23 -56 100]; mean(X)syms x y z; X = [x y z]; mean(X)median Computes the arithmetic median of the entries of a vector.X = [3 5 1 -6 23 -56 100]; median(X)min Computes the arithmetic minimum of the entries of a vector.X = [3 5 1 -6 23 -56 100]; min(X)more Turns on (or off) page-by-page scrolling of MATLAB output. Use the SPACE BARto advance to the next page, the RETURN key to advance line-by-line, and Q to abortthe output.more onmore offnotebook Opens an M-book (Windows only).notebook problem1.docnotebook -setup Glossary 307num2str Converts a number to a string. Useful in programming.constant = ['a' num2str(1)]ode45 Numerical ODE solver for first-order equations. See MATLAB's online helpfor ode45 for a list of other MATLAB ODE solvers.f = inline('tˆ2 + y', 't', 'y')[x, y] = ode45(f, [0 10], 1);plot(x, y)ones Creates a matrix of ones.ones(3)ones(3, 1)open Opens a file. The way this is done depends on the filename extension.open myfigure.figpath Without an argument, displays the search path. With an argument, sets thesearch path. Type help path for details.pretty Displays a symbolic expression in a more readable format.syms x y; expr = x/(x - 3)/(x + 2/y)pretty(expr)prod Computes the product of the entries of a vector.X = [3 5 1 -6 23 -56 100]; prod(X)pwd Shows the name of the current (working) directory.quadl Numerical integration command. In MATLAB 5.3 or earlier, use quad8 in-stead.format long; quadl('sin(exp(x))', 0, 1)g = inline('sin(exp(x))'); quad8(g, 0, 1)quit Terminates a MATLAB session.rand Random number generator; gives a random number between 0 and 1.rank Gives the rank of a matrix.A = [2 3 5; 4 6 8]; rank(A)roots Finds the roots of a polynomial whose coefficients are given by the elementsof the vector argument of roots.roots([1 2 2])round Rounds a number to the nearest integer.save Saves Workspace variables to a specified file. See also diary and load.save filename Glossary 313subplot(2, 2, 3), ezplot('xˆ4')subplot(2, 2, 4), ezplot('xˆ5')surf Draws a solid surface.[X,Y] = meshgrid(-2:.1:2, -2:.1:2);surf(X, Y, sin(pi*X).*cos(pi*Y))text Annotates a figure, by placing text at specified coordinates.text(x, y, 'string')title Assigns a title to the current figure window.title 'Nice Picture'xlabel Assigns a label to the horizontal coordinate axis.xlabel('Year')ylabel Assigns a label to the vertical coordinate axis.ylabel('Population')view Specifies a point from which to view a 3D graph.ezsurf('(xˆ2 + yˆ2)*exp(-(xˆ2 + yˆ2))'); view([0 0 1])syms x y; ezmesh(x*y); view([1 0 0])zoom Rescales a figure by a specified factor; zoom by itself enables use of the mousefor zooming in or out.zoomzoom(4)MATLAB Programmingany True if any element of an array is nonzero.if any(imag(x) ˜= 0); error('Inputs must be real.'); endall True if all the elements of an array are nonzero.break Breaks out of a for or while loop.case Used to delimit cases after a switch statement.computer Outputs the type of computer on which MATLAB is running.dbclear Clears breakpoints from a file.dbclear alldbcont Returns to an M-file after stopping at a breakpoint.dbquit Terminates an M-file after stopping at a breakpoint. 314 Glossarydbstep Executes an M-file line-by-line after stopping at a breakpoint.dbstop Insert a breakpoint in a file.dbstop in <filename> at <linenumber>dos Runs a command from the operating system, saving the result in a variable.Similar to unix.end Terminates an if, for, while, or switch statement.else Alternative in a conditional statement. See if.elseif Nested alternative in a conditional statement. See the online help for if.error Displays an error message and aborts execution of an M-file.find Reports indices of nonzero elements of an array.n = find(isspace(mystring));if ˜isempty(n)firstword = mystring(1:n(1)-1);restofstring = mystring(n(1)+1:end);endfor Repeats a block of commands a specified number of times. Must be terminatedby end.close; axes; hold ont = -1:0.05:1;for k = 0:10plot(t, t.ˆk)endfunction Used on the first line of an M-file to make it a function M-file.function y = myfunction(x)if Allows conditional execution of MATLAB statements. Must be terminated by end.if (x >= 0)sqrt(x)elseerror('Invalid input.')endinput Prompts for user input.answer = input('Please enter [x, y] coordinates: ')isa Checks whether an object is of a given class (double, sym, etc.).isa(x, 'sym')ischar True if an array is a character string. Glossary 315isempty True if an array is empty.isfinite Checks whether elements of an array are finite.isfinite(1./[-1 0 1])ishold True if hold on is in effect.isinf Checks whether elements of an array are infinite.isletter Checks whether elements of a string are letters of the alphabet.str = 'remove my spaces'; str(isletter(str))isnan Checks whether elements of an array are "not-a-number" (which results fromindeterminate forms such as 0/0).isnan([-1 0 1]/0)isnumeric True if an object is of a numeric class.ispc True if MATLAB is running on a Windows computer.isreal True if an array consists only of real numbers.isspace Checks whether elements of a string are spaces, tabs, etc.isunix True if MATLAB is running on a UNIX computer.keyboard Returns control from an M-file to the keyboard. Useful for debuggingM-files.mex Compiles a MEX program.nargin Returns the number of input arguments passed to a function M-file.if (nargin < 2); error('Wrong number of arguments'); endnargout Returns the number of output arguments requested from a function M-file.otherwise Used to delimit an alternative case after a switch statement.pause Suspends execution of an M-file until the user presses a key.return Terminates execution of an M-file early or returns to an M-file after akeyboard command.if abs(err) < tol; return; endswitch Alternative to if that allows branching to more than two cases. Must beterminated by end.switch numcase 1disp('Yes.')case 0 316 Glossarydisp('No.')otherwisedisp('Maybe.')endunix Runs a command from the operating system, saving the result in a variable.Similar to dos.varargin Used in a function M-file to handle a variable number of inputs.varargout Used in a function M-file to allow a variable number of outputs.warning Displays a warning message.warning('Taking the square root of negative number.')while Repeats a block of commands until a condition fails to be met. Must be termi-nated by end.mysum = 0;x = 1;while x > epsmysum = mysum + x;x = x/2;endmysum
Suitable for an introductory discrete mathematics course, this text covers the subfields of mathematics and computer science that fall under the general umbrella term. It fits the ideas of the basic curriculum as outlined in the SIGCSE guidelines into a framework that focuses on content rather than technique. The book covers standard and practical topics required in discrete math classes. The author also incorporates classroom activities as well as instructor's notes at the end of every chapter.
Related Lists Featured Titles Mik Wisniewski's Mathematics for Economics introduces and develops the mathematical skills and techniques necessary for any serious study of economics. The approach taken throughout the book is integrative, showing how mathematical techniques are an essential part of economic analysis. In this way the author is able to effectively illustrate the useful insights into economic behaviour that only mathematics can bring. The practical focus of the book is reflected in its modular structure, in which concepts are presented in student-friendly chunks. Each module first illustrates why economists need a particular mathematical skill or technique. Next, the key principles of that mathematical technique are developed and explained. Finally, we see how that technique can be applied to common economic situations in order to improve our understanding of economic principles and behaviour. Key features of the third edition include: • A clear focus on the practical usefulness of mathematics to economic analysis • A gradual progression of mathematical material throughout the text • Ideal for students who have a limited mathematical background, but provides pathways for students to proceed at their own pace • Progress Check and Knowledge Check activities throughout each module, so that students can check their own understanding • Fully-worked examples are integrated into the end of each module showing a more complete and complex application to the student • New module on probability in economic analysis Available to lecturers: Access to a companion website at which includes PowerPoint slides and an instructor's resource manual containing fully worked solutions to end-of-module exercises, as well as additional exercises for each module. About the Author(s) MIK WISNIEWSKI is a Senior Research Fellow at the University of Strathclyde Business School, UK where he has specific research interests in performance measurement and performance management, particularly for public sector organisations. His research expertise relates to benchmarking, process mapping and the use of the balanced scorecard as well as business analysis and modelling. He has extensive teaching and consultancy experience across the UK, Europe, Africa and the Middle East in the areas of economic analysis, modelling and forecasting. He has worked with companies such as British Energy, British Gas, Shell, Scottish Power and with a variety of public sector organisations. Table of Contents Introduction PART I: THE BUILDING BLOCKS OF ECONOMIC ANALYSIS Tools of the Trade: the Basics of Algebra Linear Relationships in Economic Analysis Non-linear Relationships in Economic Analysis PART II: LINEAR MODELS IN ECONOMIC ANALYSIS The Principles of Linear Models Market Supply and Demand Models National Income Models Matrix Algebra - the Basics Matrix Algebra - the Matrix Inverse Economic Analysis with Matrix Algebra Economic Analysis with Matrix Algebra: Input-output Analysis PART III: OPTIMIZATION IN ECONOMIC ANALYSIS Quadratic Functions in Economic Analysis The Derivative and the Rules of Differentiation Derivatives and Economic Analysis The Principles of Optimization Optimization in Economic Analysis Optimization in Production Theory PART IV: OPTIMIZATION WITH MULTIPLE VARIABLES Functions of More Than Two Variables Analysis of Multi-variable Economic Models Unconstrained Optimization Constrained Optimization PART V: FURTHER TOPICS IN ECONOMIC ANALYSIS Integration and Economic Analysis Financial Analysis in Economics I: Interest and Present Value Financial Analysis in Economics II: Annuities, Sinking Funds and Growth Models An Introduction to Dynamics Probability and Economic Analysis Appendices The Greek Alphabet Solutions to the Learning Check Activities Solutions to the Progress Check Activities Outline Solutions to the End-of-module Exercises
Prealgebra (Cloth) - 6th edition Summary: Elayn Martin-Gay firmly believes that every student can succeed, and her developmental math textbooks and video resources are motivated by this belief. ''Prealgebra,'' Sixth Edition was written to help students effectively make the transition from arithmetic to algebra. The new edition offers new resources like the Student Organizer and now includes Student Resources in the back of the book to help students on their quest for success. Whole Numbers and Introduction to Algebra; Intege...show morers and Introduction to Solving Equations; Solving Equations and Problem Solving; Fractions and Mixed Numbers; Decimals; Ratio, Proportion, and Triangle Applications; Percent; Graphing and Introduction to Statistics; Geometry and Measurement; Exponents and Polynomials For all readers interested in prealgebra. ...show less 032164008X67 +$3.99 s/h Acceptable Sierra Nevada Books Reno, NV Biggest little used bookstore in the world. $177
This book was written to help mathematics students and those in the physical sciences learn modern mathematical techniques for setting up and analyzing problems. The mathematics used is rigorous, but not overwhelming, while the authors carefully model physical situations, emphasizing feedback amonConcepts of Mathematical Modeling by Walter J. Meyer This text features examinations of classic models and a variety of applications. Each section is preceded by an abstract and statement of prerequisites. Includes exercises. 1984Differential Equations with Applications by Paul D. Ritger, Nicholas J. Rose Coherent introductory text focuses on initial- and boundary-value problems, general properties of linear equations, and differences between linear and nonlinear systems. Answers to most problems. The Electromagnetic Field by Albert Shadowitz Comprehensive undergraduate text covers basics of electric and magnetic fields, building up to electromagnetic theory. Related topics include relativity theory. Over 900 problems, some with solutions. 1975 edition. Treatise on Thermodynamics by Max Planck Great classic, still one of the best introductions to thermodynamics. Fundamentals, first and second principles of thermodynamics, applications to special states of equilibrium, more. Numerous worked examples. 1917 edition. Stochastic Modeling: Analysis and Simulation by Barry L. Nelson Coherent introduction to techniques also offers a guide to the mathematical, numerical, and simulation tools of systems analysis. Includes formulation of models, analysis, and interpretation of results. 1995 Chapter TheReprint of the Prentice-Hall, Englewood Cliffs, New Jersey, 1988
This package consists of the textbook plus an access kit for MyMathLab/MyStatLab. Elementary Statistics: Picturing the World, Fifth Edition, offers our most accessible approach to statistics-with more than 750 graphical displays that illustrate data, students are able to visualize key statistical concepts immediately. Adhering to the philosophy that students learn best by doing, this book relies heavily on examples ;25% of the examples and exercises are new for this edition. Larson and Farber continue to demonstrate that statistics is all around us and that it's easy to understand. MyMathLabprovides a wide range of homework, tutorial, and assessment tools that make it easy to manage your course online
Mathematics for Class 8 (Paperback) Price: Rs.166 Mathematics for Class-VIII is a reference book for the students of class VIII. Written by R. S. Aggarwal, this book is based on the latest syllabus prescribed by the CBSE board. It is a popular book among students as they find it clear and simple to use. Written in a concise style, the book provides to the point information for the students. Solved problems related to all the topics have been integrated so that the students can get a feel of the questions that they will have to face in the examination. Graded exercises and a few test papers give an added advantage to the students going through this book. The various important topics covered in this book are rational numbers, exponents, squares and square roots, cubes and cube roots, playing with numbers, operations on algebraic expressions, factorization, linear equations, percentage, profit and loss, compound interest, direct and inverse proportions, and time and work. Moreover, various crucial topics of geometry have been included in this book such as polygons, quadrilaterals, parallelograms, construction of quadrilaterals, area of a trapezium and a polygon, three-dimensional figures, and volume and surface area of solids. The students will also get to understand the nuances of data handling, construction and interpretation of bar graphs, pie charts, probability, and graphs. Several activities and the last section on answers ensure that the students can practice their knowledge and understanding of the subject in a better way. R. S. Aggarwal is the author of this book. Other famous books written by him include Quantitative Aptitude For Competitive Examinations, A Modern Approach To Verbal & Non-Verbal Reasoning, Objective General English, Advance Objective General Knowledge, Quick Learning Objective General English, Secondary School Mathematics For Class - 10, and many others. I have bought this book from flipkart and yes this is awesone. It has all the concept of mathematics with examples and answers on back. This is my third book of R S Aggarwal. He is a great man. And no doubt flipkart is the best. The questions are tricky but it is under the limit of solving. The examples are well ilustrated. The best thing is that at the end of every chapter there is 'Things to Remember' and 'CCE Test Paper'. Thank you R S aggarwal and very special thank you Flipkart. I get these books at school (National Public School). They are absolutely amazing! I'm in grade 8 and I have the exact same book. Probably the best maths book for CBSE schools. It will help you understand your concepts better.
part of the NCTM's Student i-Math Investigations website. It uses algebra and discrete mathematics to analyze population changes in a trout pond. Included are applets for numerical and graphical analysis.
Class Schedule Detail 2013 Fall - MATH Subj Cat# Class# Sect Course MATH 231PO 1015 1 Principles of Real Analysis I Description By looking carefully at the concept of distance and the notion of an abstract metric space, we will gain a deeper understanding of the Real numbers and of what makes calculus work. Topics will include uncountability, connectedness, and compactness. We will look at continuity in terms of open and closed sets. Offered alternate Fall semesters.
0534381251 next business day.Read moreShow Less More About This Textbook Overview Helping students grasp the "why" of algebra through patient explanations, Hirsch and Goodman gradually build students' confidence without sacrificing rigor. To help student definitions through a wealth of illustrative examples - both numerical and algebraic-helps students compare contrast related ideas and understand the sometimes subtle distinctions among a variety of situations. The authors emphasize problem analysis and model building. For example, new sections help students identify and develop useful strategies for recognizing mathematical relationships as a first step in the process of solving
Subject: Mathematics (9 - 12) Title: Zero to Hero in Quadratics Description: Students will solve quadratics using a variety of methods and discover that the quadratic method is related to solving equations. Students prerequisite skills are solving equations, factoring, and substitution. This is a College- and Career-Ready Standards showcase lesson plan. Subject: Mathematics (9 - 12) Title: Now, where did THAT come from? Deriving the Quadratic Formula Description: Generally, teachers expect students to memorize the quadratic formula and to know that you use it after exhausting all other means of solving a quadratic equation, i.e. as a last resort. This technology-based lesson is designed to assist students with deriving the formula on their own. Students must first be familiar with complex numbers and the process of "completing the square." This lesson plan was created by exemplary Alabama Math Teachers through the AMSTI project.
Math Proofs Demystified Overview Almost every student has to study some sort of mathematical proofs, whether it be in geometry, trigonometry, or with higher-level topics. In addition, mathematical theorems have become an interesting course for many students outside of the mathematical arena, purely for the reasoning and logic that is needed to complete them. Therefore, it is not uncommon to have philosophy and law students grappling with proofs. This book is the perfect resource for demystifying the techniques and principles that govern the mathematical proof area, and is done with the standard "Demystified" level, questions and answers, and accessibility1469923 There are no customer reviews available at this time. Would you like to write a review?
This brand new series has been written for the University of Cambridge International Examinations course for AS and A Level Mathematics (9709). This title covers the requirements of M1 and M2. The authors are experienced examiners and teachers who have written extensively at this level, so have ensured all mathematical concepts are explained using... more... Introduction to Computational Modeling Using C and Open-Source Tools presents the fundamental principles of computational models from a computer science perspective. It explains how to implement these models using the C programming language. The software tools used in the book include the Gnu Scientific Library (GSL), which is a free software library... more... Learn a lot about science as you make models showing how things work! A spectacular model of an active volcano . . . a fascinating representation of the solar system . . . scale reproductions of atoms and molecules . . . In Janice VanCleave's Super Science Models, America's favorite science teacher shows you how to make these and other eye-catching... more... Contains a comprehensive study of the basic concepts and principles of variational analysis and generalized differentiation in both finite-dimensional and infinite-dimensional spaces and presents numerous applications to problems in optimization, equilibria, stability and sensitivity, control theory, economics, mechanics, and more. more... Science and engineering students depend heavily on concepts of mathematical modeling. In an age where almost everything is done on a computer, author Clive Dym believes that students need to understand and "own" the underlying mathematics that computers are doing on their behalf. His goal for Principles of Mathematical Modeling, Second Edition , is... more...
More About This Textbook Overview Algebra, the foundation for all higher mathematics, is taught here both for beginners and for those who wish to review algebra for further work in math, science and engineering. This superior study guide­­the first edition sold more than 600,000 copies!­­includes the most current terminology, emphasis and technology. It treats many subjects more thoroughly than most texts, making it adaptable for any course and an excellent reference and bridge to further study. Also available as a Schaum's Electronic Tut
by Step Approach, 6thedition. This softcover edition includes all the features of the longer book, ... Browse A STEP BY STEP APPROACH is for general beginning statistics courses with a basic algebra prereq- TEXT: A Brief Version- ElementaryStatistics- A Step by Step Approach, 6thEdition, By Allan G. Bluman MATERIALS: You will need a TI-83 or TI-84 graphing calculator for this class. You will also need a Connect Math student access kit. Textbook: ElementaryStatistics a Step by Step Approach, 6thEdition by Allan Bluman, McGraw/Hill, 2006. Available at Alsheqary bookstore ... Introductory statistics is a not an easy course and much of the material needs to be ... particularly for the Academic Support Classes that support the 6th, ... ElementaryStatistics: Picturing the World. Larson Statistical Reasoning for ... Smith ElementaryStatistics: A Step by Step Approach. Bluman Discrete Mathematics and its Applications.
Introductory Physics Student Solutions94 FREE About the Book For over two decades, physics education research has been transforming physics teaching and learning. Now in this new algebra-based introductory physics text, Jerry Touger taps this work to support new teaching methodologies in physics. "Introductory Physics: Building Understanding" recognizes that students learn better in guided active learning environments, engages students in a conceptual exploration of the physical phenomena before mathematical formalisms, and offers explicit guidance in using qualitative thinking to inform quantitative problem solving.
Math - Fall 2013 Prerequisite: Enrollment requires approval of the Director of the Math Workshop. A graded, non-credit course moving from elementary algebra through more complex concepts, with the objective of producing readiness for college-level work in mathematics and math-related courses. Topics include real numbers, simple operations on polynomials, solving and graphing linear equations, algebraic fractions, fractional equations, and exponential and logarithmic functions, as well as other more advanced topics which will prepare students for statistics or pre-calculus if desired. This course is taught using a web-based, artificially intelligent assessment and learning system called ALEKS which individualizes the curriculum to the students' needs. A grade of 80% or higher in the respective ALEKS course (Math Placement Level 22, 23 or 24) constitutes a passing grade in MATH 090. This course only serves to help students raise the second digit of their math placement score. MATH 118 Mathematics for Elementary and Middle School Teachers 4 credits Lewis, Obed Prerequisite: Math Placement Level 22 or higher Study of number systems, number theory, patterns, functions, measurement, algebra, logic, probability, and statistics with a special emphasis on the processes of mathematics: problem solving, reasoning and proof, communicating mathematically, and making connections within mathematics and between mathematics and other disciplines. Open only to students intending to major in education. Every year. Mathematical-reasoning intensive. Prerequisite: MATH 118 Study of basic concepts of plane and solid geometry, including topics from Euclidean, transformational, and projective geometry with a special emphasis on the processes of mathematics: problem solving, reasoning and proof, communicating mathematically, and making connections among mathematical ideas, real-world experiences, and other disciplines. Includes computer lab experiences using Geometer's Sketchpad. Open only to students majoring in education. Every year. Mathematical-reasoning intensive. MATH 120 Elementary Functions 4 credits Ben-azzouz, Moez Prerequisite: Math Placement Level 24 or higher This is a standard pre‑calculus mathematics course that explores the functions common to the study of calculus. Examination of polynomial, rational, exponential, logarithmic, and trigonometric functions will be done using algebraic, numeric, and graphical techniques. Applications of these functions in formulating and solving real-world problems will also be discussed. The final grade in the course will be based on homework, quizzes, tests, and a comprehensive final exam. Students are required to have a TI-83, TI-84, or TI-86 graphing calculator for use in class and for homework assignments. Mathematical-reasoning intensive. MATH 127 Introductory Statistics 4 credits Lewis, Obed Prerequisites: Math Placement Level 23 or higher A study of statistics as the science of using data to glean insight into real-world problems. Includes principles and methods for describing and summarizing data, sampling procedures and experimental design, inferences about the real-world processes that underlie the data, and student projects for collecting and analyzing data. Open to non-majors only. Note: A student may receive credit for only one of the following statistics courses: MATH 127, MATH 227, PSYC 107, or MGT 210. Mathematical-reasoning intensive. MATH 131 Essentials of Calculus 4 credits Shelburne, Brian Prerequisite: MATH 120 or Math Placement Level 25 This one semester calculus course is an introduction to the techniques and applications of differential and integral calculus. The applications come primarily from the economics and bio-sciences and do not involve any trigonometric models. The final grade in the course will be based on homework, quizzes, tests, and a comprehensive final exam. Students are required to have a TI-83, TI-84, or TI-86 graphing calculator for use in class and for homework assignments. Mathematical-reasoning intensive. Notes: 1. Students may not receive credit for both MATH 131 and MATH 201 2. MATH 131 does not satisfy the prerequisite for MATH 202: Calculus II. 3. Take MATH 131 only if you are positive that you will take only one semester of calculus at Wittenberg. Otherwise, you should take the MATH 201 – MATH 202 sequence. MATH 171 Discrete Mathematical Structures 4 credits Shelburne, Brian Prerequisite: Math Placement Level 25 Discrete Mathematical Structures covers a number of mathematical topics which are central to both mathematics and computer science, topics centering on the mathematics of discrete sets, that is, sets which are finite or at most countably infinite. Starting on the foundation of logic, set theory and basic proof techniques, the course will cover relations and functions, counting arguments, discrete probability, number theory and graph theory. The course is required for the major in computer science and can be used as an elective for the computer science minor. The course grade will be determined by quizzes, homework assignments, in-class tests and a comprehensive final. Mathematical-reasoning intensive. Prerequisite: MATH 120 or Math Placement Level 25 Calculus is the mathematical tool used to analyze changes in physical quantities. This is the first course in the standard calculus sequence. It develops the notion of "derivative", which is used for studying rates of change, and then introduces the concept of "definite integral", which is related to area problems. The overall approach will emphasize the concepts of calculus using graphical, numerical, and symbolic methods. The two-semester calculus sequence, MATH 201/202, is required for all students majoring in mathematics, physics, or chemistry, or minoring in mathematics. MATH 201 and MATH 202 can also count as supporting science courses for the BA and BS programs in Biology, Geology, and Biochemistry/Molecular Biology. Students who are sure they will take only one semester of calculus may be better served in the single-semester introduction to calculus, MATH 131: "Essentials of Calculus". Students majoring in computer science must take either Math 131 or Math 201/202. Talk with your advisor or with any math professor for advice on which calculus course is most appropriate for you. Students could be based on homework, quizzes, tests, and a comprehensive final exam. Mathematical-reasoning intensive. NOTE: Students may not receive credit for both MATH 131 and MATH 201. MATH 202 Calculus II 4 credits Parker, Adam Prerequisite: MATH 201 This is the second course in Wittenberg's three semester calculus sequence. MATH 202 is primarily concerned with integration and power series representations of functions. Topics covered include indefinite and definite integrals, the Fundamental Theorem of Calculus, integration techniques, approximations of definite integrals, improper integrals, applications of integrals, power series, Taylor series, geometric series, and convergence tests for series. Normally, students will be based on quizzes, tests, and a comprehensive final exam. Mathematical-reasoning intensive. MATH 205 Applied Matrix Algebra 4 credits Higgins, William Prerequisites: MATH 201 A course in matrix algebra and discrete mathematical modeling which considers the formulation of mathematical models, together with analysis of the models and interpretation of the results. Primary emphasis is on those modeling techniques which utilize matrix methods. Such methods are now in wide use in areas such as economic input‑output models, population growth models, Markov chains, linear programming, computer graphics, regression, numerical approximation, and linear codes. Students in this course are required to have a TI-83, TI-84, or TI-86 calculator for use in class, for homework, and for tests. A TI-89, TI-92, or Voyage 200 is also acceptable. The final grade in the course is based on quizzes, tests, and a comprehensive final exam. This course is a prerequisite for MATH 360 (Linear Algebra), and should be taken by all sophomore mathematics majors. Mathematical-reasoning intensive. The final grade in this course is based on quizzes, tests, homework and a comprehensive final exam. Mathematical-reasoning intensive. MATH 221 Foundations of Geometry 4 credits Parker, Adam Prerequisite: MATH 210 A rigorous study of Euclidean and non-Euclidean geometry from an axiomatic point of view. Special attention is given to the concepts of definition, theorem, and proof. The mathematics is studied in an historical context. This course is primarily intended for junior/senior mathematics majors and minors, and should be of particular interest to those planning to teach mathematics at a pre‑college level. The course is writing intensive. Mathematical-reasoning intensive. MATH 227 Data Analysis 4 credits Andrews, Douglas Prerequisite: MATH 131 or MATH 201 This introductory statistics course is designed not only for students majoring or minoring in math, but for any student who would benefit from a more substantial introduction to the field - especially prospective teachers of mathematics or statistics, as well as students considering careers as statisticians or actuaries. Students will learn general principles and techniques for summarizing and organizing data effectively, and will explore the connections between how the data was collected and the scope of conclusions that can be drawn from the data. Also emphasized are the logic and techniques of formal statistical inference, with greater focus on the mathematical underpinnings of these basic statistical procedures than is found in other introductory statistics courses. Software for probability and data analysis is used daily. Note: A student may not receive credit for more than one of the following: MATH 127, MATH 227, PSYC 107, or BUSN 110. Mathematical-reasoning intensive. Prerequisites: MATH 131 or both MATH 201 and 202 Introduction to the principles and approaches of using computational science through the use of problem solving methodologies. This includes the understanding, development, and use of mathematical models, as well as their effective computer implementation. Approximately fifteen approaches across eight categories (continuous and discrete, static and dynamic, empirical and formulated) will be investigated. These models are adapted from a variety of scientific and real-world scenarios. Simulation and optimization techniques will also be discussed and used. Each student will undertake a realistic modeling project as part of the course. Laboratory required. This course is cross-listed as COMP 260. Students may enroll in either COMP 260 or MATH 260, but not both. Mathematical-reasoning intensive. MATH 328 Mathematical Statistics 4 credits Andrews, Doug Prerequisites: MATH 228 Essential for anyone interested in a career in statistics or actuarial science, this course extends the ideas of Univariate Probability (MATH 228) to probability of several variables, which is then used to explore the distribution theory underlying the most commonly, used statistical methods. Mathematical-reasoning intensive. MATH 360 Linear Algebra 4 credits Higgins, William Prerequisites: MATH 205 and MATH 210 Introduction to abstract vector spaces. Topics include Euclidean spaces, function spaces, linear systems, linear independence and basis, linear transformations and their matrices. Students are required to have a TI-83, TI-84, or TI-86 graphing calculator for use in class, for homework, and on tests. A TI-89, TI-92, or Voyage 200 is also acceptable. The final grade in the course is based on written assignments, quizzes, tests, and a comprehensive final exam. Writing intensive. Mathematical-reasoning intensive. MATH 370 Real Analysis 4 credits Parker, Adam Prerequisite: MATH 210 Through a rigorous approach to the usual topics of one‑dimensional calculus ‑ limits, continuity, differentiation, integration, and infinite series ‑ this course offers a deeper understanding of the ideas encountered in calculus. The course has two important goals for its students: the development of an accurate intuitive feeling for analysis and of skill at proving theorems in this area. The final grade in this course is based upon written assignments, tests, and a comprehensive final exam. Writing intensive. Mathematical-reasoning intensive. MATH 460 Senior Seminar 2 credits Shelburne, Brian Prerequisite: Senior math major or permission of instructor This is a capstone course for mathematics majors. Its purpose is to let participants think about and reflect on what mathematics is and to tie together their years of studying mathematics at Wittenberg. The structure of the course will be taken from the book Journey Through Genius by W. Dunham which covers the story of mathematics from the 5th century B.C.E. up to the 20th century C.E. by looking at some of the famous problems, theorems, and "colorful" mathematical characters who worked on them. The course is a seminar where participants are expected to research areas of interest in mathematics and present their findings to the rest of the seminar. The grade will be based on class discussions, problem write-ups, in class presentations and an expository paper on some mathematical subject. Mathematical-reasoning intensive. Writing intensive.
Adam B. Levy Other Titles in Applied Mathematics 114 This textbook provides undergraduate students with an introduction to optimization and its uses for relevant and realistic problems. The only prerequisite for readers is a basic understanding of multivariable calculus because additional materials, such as explanations of matrix tools, are provided in a series of Asides both throughout the text at relevant points and in a handy appendix. The Basics of Practical Optimization presents • step-by-step solutions for five prototypical examples that fit the general optimization model, • instruction on using numerical methods to solve models and making informed use of the results, • information on how to optimize while adjusting the method to accommodate various practical concerns, • three fundamentally different approaches to optimizing functions under constraints, and • ways to handle the special case when the variables are integers. The author provides four types of learn-by-doing activities through the book: • Exercises meant to be attempted as they are encountered and that are short enough for in-class use • Problems for lengthier in-class work or homework • Computational Problems for homework or a computer lab session • Implementations usable as collaborative activities in the computer lab over extended periods of time The accompanying Web site offers the Mathematica notebooks that support the Implementations. Audience This textbook is appropriate for undergraduate students who have taken a multivariable calculus course. About the Author Adam Levy is Professor and Chair of the Department of Mathematics at Bowdoin College. He was recognized in 1997 with the college's Sydney B. Korofsky prize for excellence in undergraduate teaching and has published over two dozen journal articles on optimization.
Mathematical Content Strands Number sense, properties, and operations This content area focuses on students' understanding of numbers (whole numbers, fractions, decimals, integers, real numbers, and complex numbers), operations, and estimation, and their applications to real-world situations. Students are expected to demonstrate an understanding of numerical relationships as expressed in ratios, proportions, and percents. Students are also expected to understand properties of numbers and operations, generalize from numerical patterns, and verify results. Measurement This content area focuses on an understanding of the process of measurement and on the use of numbers and measures to describe and compare mathematical and real-world objects. Students are asked to identify attributes, select appropriate units and tools, apply measurement concepts, and communicate measurement-related ideas. Geometry and spatial sense This content area extends beyond low-level identification of geometric shapes into transformations and combinations of those shapes. It focuses on informal constructions and demonstrations, along with their justifications. Geometry and spatial sense area includes the demonstration of reasoning within both formal and informal settings. Proportional thinking to similar figures and indirect measurement is an important connection in this area. Data analysis, statistics, and probability This content area focuses on the skills of collecting, organizing, reading, representing, and interpreting data. These are assessed in a variety of contexts to reflect the use of these skills in dealing with information. Students are expected to use statistics and statistical concepts to analyze and communicate interpretations of data. Students are also expected to understand the meaning of basic probability concepts and applications of these concepts in problem-solving and decision-making situations. Algebra and functions This content area extends from work with simple patterns, to basic algebraic concepts, to sophisticated analysis. Students are expected to use algebraic notation and thinking in meaningful contexts to solve mathematical and real-world problems, addressing an increasing understanding of the use of functions as a representational tool. Other topics assessed include using open sentences and equations as representational tools and using the notion of equivalent representations to transform and solve number sentences and equations of increasing complexity. Last updated 3 October 2003 (JM) Would you like to help us improve our products and website by taking a short survey?
Prerequisite: Placement through the assessment process or MATH 075 or MATH 075SP or equivalent Note: This section is an optional part of DVC''s Umoja Program. Students must enroll in both HIST-128-6365 and CARER-110MATH-090 6367 TTH 9:30-11:45am MA-245 5 Units Full Term Catalog Course Description MATH-090 Elementary Algebra 5 - 5 Units SC Not Degree Applicable Variable Hours Prerequisite: Placement through the assessment process or MATH 075 or MATH 075SP or equivalent Formerly MATH 110 This course is an introduction to the techniques and reasoning of algebra, including linear equations and inequalities, development and use of formulas, algebraic expressions, systems of equations, graphs and introduction to quadratic equations.
Math Autobiography/ Intro. Assignment Due Tuesday, 9/11 Between now and Tuesday, 9/10 please send me an e-mail at vittoria_macadino@newton.k12.ma.us with this assignment that is meant to help me get to know you better as a person and as a math student. Please use an email account that you check regularly and ATTACH your paper to the email as a word document. You must include information on three things: Names and preferred telephone number and email address(es) for contacting your parent(s) or guardians. You may put this in the body of the email message itself. Describe yourself as a person. In your first one or two paragraphs, tell me a little bit about you as a person. Tell me where you grew up, if you've always attended Newton Public Schools, how many siblings you have. Mention a few of your activities and hobbies, talents and passions, values and commitments. What are the important things that you want me to know about you? Any favorite movies, TV shows, artists, musicians/bands? Do you speak any other languages? Have you traveled some place exotic? Describe yourself as a math student. Think about your past and present mathematics experiences. Which math classes have you taken already and who was your previous teacher? What have been your best and worst experiences related to math? What kinds of math class activities do you like and dislike? When has learning math been easy, and when has it been hard? What do you like and dislike about math itself? What are your goals for this math class? And finally, whatever else you consider important about you and math. I particularly enjoy stories. [Note: If you arrived at NSHS recently, be sure to describe the math classes you took at your previous school.] GUIDELINES: You must type your paper using correct English spelling and grammar. Your paper must be at least 300 words long. (That's about 1 page typed, double spaced with 1-inch margins and 12-pt font.) It may be (and probably will be) longer, but please no more than 900 words (3 pages typed). If you do not meet the length requirement, you cannot earn a grade higher than a C on this paper. I am giving this assignment in multiple classes, so in the SUBJECT LINE of your email, please write your name, and which course and section you are in (e.g. Mary Jones 612 Block A). This assignment will count as a 10 point collected assignment. I will ask myself the following questions about your paper as I grade it: How much did I learn about this student? Is the paper clear and well written? Did this student follow the guidelines for length and form? Did this student use correct English grammar and structure? Did this student follow the guidelines for content? Did this student appear to put real effort into the assignment?
Practice Papers for SQA Exams - Intermediate 2 Maths | Units 1,2,3 Grade(s): Intermediate 2 Author(s): Ken Nisbet ISBN: 9781843727781 This The questions are supported with fully worked answers that clearly explain how to understand and tackle each question, how to reach the right answer and how to maximise marks in the final exam. Our Practice Papers can be used in two main ways. You can either work completely through each paper, treating it as a timed practice-run for the final exam; or you can use the index of topic questions in order to find and focus on the topics that you particularly need to revise. Just click on the online resources tab below to find out more about this really helpful feature! The enhanced answer section for each Practice Paper is specifically designed to ensure you understand your course material as fully as possible. These sections will build confidence in answering exam questions - they show exactly what the examiner is looking for and how you can set about getting those all important extra marks! Practical revision tips are also provided, making the Practice Paper a one-stop shop for all revision needs! Completely new practice papers, available for the first time Enhanced answer section supports learning by demonstrating how to arrive at the correct answer Marking schemes allow you to see how marks are allocated, which helps plan time effectively during the exam Highly effective for use in class or for revision at home Designed to look and feel just like an SQA exam paper to mirror the exam experience Packed full of practical exam hints and tips Choose whether to complete a whole paper or let the handy topic index allow you to focus on specific topics The perfect revision tool for students wanting to practise exams questions and understand how to achieve the very best grade Unlimited lifespan as papers are not year-dependent Competitively priced to help stretch your budget! TEACHERS! There is a FREE PDF version of this product for whiteboard use available to you when you purchase 20 copies of more of this book. It will simply be added to your order. It's the perfect tool to help you make revision preparation that little bit easier …
Students watch video lectures on CD-ROM and do problems from the 753-page workbook. When they need help or review, you've got a printed Answer Key plus audiovisual step-by-step solutions to every homework and quiz problem. Sample Pages Sample Lectures TheLecture & Practice CD'scontain 10-15 minute lectures for every lesson in the print textbook. They also feature multimedia step-by-step explanations to the 5 practice problems that accompany each lesson. This set of CDs is ideal for students who prefer listening and watching to reading. Sample Solutions TheSolution CD's contain a multimedia step-by-step explanation to every single one of the almost 3,000 homework problems in the textbook. If you're tired of having to help your child do half his homework, or if you simply want to give him access to a library of quality explanations which will undoubtedly supplement and reinforce his understanding, this is the tool you need. by Jennifer S on 2013-08-30 I have used Saxon with my children from Math K through Algebra 2. So far we are extremely disappointed with Teaching Textbooks Geometry. The lessons are too fast and easy for students used to the rigors of Saxon. by MELISSA H on 2009-01-28 My first child took Saxon Alg 1 and 2 and did not score as high on his PSAT in the geometry area even though Saxon covers it. Supplemented with TT and his score was much higher. I love the way the concepts are explained and how my child can work independently.
Book Description Revise AS & A2 Mathematics gives complete study support throughout the two A Level years. This Study Guide matches the curriculum content and provides in-depth course coverage plus invaluable advice on how to get the best results in the exams Revise AS & A2 Mathematics gives complete study support throughout the two A Level years. This Study Guide matches the curriculum content and provides in-depth course coverage plus invaluable advice on how to get the best results in the exams {"currencyCode":"GBP","itemData":[{"priceBreaksMAP":null,"buyingPrice":17.99,"ASIN":"1843154773","isPreorder":0},{"priceBreaksMAP":null,"buyingPrice":12.23,"ASIN":"1843159287","isPreorder":0},{"priceBreaksMAP":null,"buyingPrice":12.23,"ASIN":"1843159279","isPreorder":0}],"shippingId":"1843154773::gY1C1mgs9VolfL1zZY%2F20KXa21Y%2FMgnH5SN0YAlg0E6RYS6qRMss3jDT3QEcp%2BJmlxzv9smO2s7KKRQosIz6oM3AOyayqWox,1843159287::Tn%2FWRbVsLlFNmqRYXe0l8YO1Y6hw7Q7nIZpQHjz2rZTMXvwmLRGm5pjAUzZVEK9fHOZIq%2FGq9cWObNHCEL%2BoRMM%2FGU5Fenp4,1843159279::sm3VHOSwrmn%2B8vEiz9SI%2B7xaF7RCDzpUPKxmWxEpHXMan%2B9eW%2FLHg3kJPDv44PmP%2FCa3JgUhO5k8U1g4DFWu7orkuP4fE%2Fb book is very useful; it explains everything very clearly and concisely and there are frequent questions. The divisions also make it very easy to do a little revision at a time. The only downside; as it is for all exam boards there is some irrelavant material I am currently taking A2 maths - WJEC exam board. I have been looking everywhere for a book that covers my exam board and finally i have found one!! It covers MOST of my topics - i think theres one which isnt in there. This book is fantastic for revision, it lays everything out in an easy and understandable format. Its a big book but dont let that put you off not all the stuff inside has anything to do with your exam board. I think its a MUST have if your taking A level maths. This book is a great summary, with clear topic explanations and an invaluable guide showing which topics are included for each paper of each board. Each topic is clearly and concisely explained, with liberal use of diagrams. This probably wouldn't be a good book to try to learn from, as the explanations are brief, but it's a great tool for revision (which is the aim of the book). Having read the maths one, I bought the biology and chemistry ones without hesitation or even looking at other books. this product is really good it has lots of information for a level which would help me in the future 2 years of a level. For the price i paid (£2.80 From Brit Books Ltd ) the book was in perfect condition. Only the cover was partly bent which i didn't care. I recommend this book for anyone who is doing A level maths. When buying this product, you may think its not enough, but the book is designed to give you enough information for each topic. Best Buy Ever!!
1) Is it the most efficient to read through the chapters, and write down theorems, definitions, and take notes of important parts and work out all the proofs and examples? And then make sure you can re-prove everything after finishing a chapter? Like for example, studying analysis, topology, etc. And the same with physics. Or is it better to just do all the problems and move on? What would be the most efficient method of studying considering time and being able to understand it 100%? Like, I know it's good to use multiple books too, and the optimal method would be to work out everything, but it seems too time-consuming to be able to learn enough and go into the research field and publishing faster. 2) And how long does it usually take one to finish a textbook? What are the advantages to taking a class than self-studying assuming one would put in as much work as needed if one had to take a final exam? 3) And where exactly does talent play in the process? Is it just about understanding things quicker and applying it more efficiently? I find that I can do math and physics with relative ease; are there people with varying degrees of talent and how pertinent is it to have the "most" talent in terms of being one of the top in math and physics research career? 4) By the way, just one more question, how important is like physics or math competitions to physics or math careers in research? I only got interested in these subjects very recently, so although they were my best subjects in school and I understood them easily, I never really practiced for olympiads or anything. And the only thing I did regarding competitions was math team and contests like ARML. 3) Talent can help a little, but research is more about hard work: terrytao.wordpress.com/career-advice/… 4) Contest math is almost completely irrelevant to research. Research takes a long time, nobody currently knows the answer to your research problem, and you are free to consult sources. Contests have a short time limit, you are typically allowed no references, a known answer exists, and moreover many contest problems tend to revolve around some very particular clever trick. – Henry T. HortonAug 19 '13 at 3:25 So contests are mostly about practice and experience? Does talent mostly help in understanding and being able to apply new concepts easier? What do you think about my other questions? thanks. – Benny ChangAug 19 '13 at 4:18 1 Answer The most efficient way to learn something is to teach/explain it to a layman. (e.g. answering question on MSE). The process forces you to organize your thoughts and identify the key ingredients and connections for the topic at hand. This leaves a deeper imprint on your neural network. Creating your own notebook, revisit it frequently and regularly drawing pictures to summarize the relationship also helps. The time to finish a textbook strongly depends on your age. When I'm a teenage, I can finish a math/physics textbook in a day but now it will probably take me more than a few weeks. The key is to learn math/physics as early as possible when your brain is still fresh. The advantage of taking a class is it help you to identify the important pieces in the material and help you to remember it longer (assume you are lucky and don't have a sleep-inducing professor). No comment. Once you get into research, math/physics competitions becomes completely irrelevant. People judge you by what sort of result you can produce. However, it does help you in getting accepted by a University. It also give you an edge when you apply for a non-academic job that value math skill (e.g. financial industry). Is it really possible to finish a text in one day? I've been working on Hubbard and each section takes at least 3-4 hours to write all the important things out and go through all the problems – Benny ChangAug 19 '13 at 15:33 @BennyChang it depends on the thickness of the book, the level of the material and how good does the author present it. One advantage of youth is one has a much better short-term memory. For elementary/introductory text book, a lot of statement/problem becomes obvious if you remember the hints in previous Chapter. As we age, we lost that advantage. That's why creating your personal notebook is useful. It help you to mark down the important concepts which you will need in later part of your reading. – achille huiAug 19 '13 at 15:59 +1 I deleted my answer, as this is better. – user83622Aug 19 '13 at 21:49 Thanks for the thorough answer. Is there a specific method to studying these subjects in general that's usually more efficient and helps to understand and retain the most? And any other opinions on 3? – Benny ChangAug 19 '13 at 23:06 @BennyChang, Nothing specific I can think of. If you are lucky and can find someone around same level of sophistication as you, then frequent exchange of ideas / intuitions / understandings will make the process more interesting and effects long lasting. No comment about 3. Independent of how much talent you have, one should really do math/physics simply because you find it interesting. – achille huiAug 20 '13 at 9:13
More About This Textbook Overview Mathematical physics provides physical theories with their logical basis and the tools for drawing conclusions from hypotheses. Introduction to Mathematical Physics explains to the reader why and how mathematics is needed in the description of physical events in space. For undergraduates in physics, it is a classroom-tested textbook on vector analysis, linear operators, Fourier series and integrals, differential equations, special functions and functions of a complex variable. Strongly correlated with core undergraduate courses on classical and quantum mechanics and electromagnetism, it helps the student master these necessary mathematical skills. It contains advanced topics of interest to graduate students on relativistic square-root spaces and nonlinear systems. It contains many tables of mathematical formulas and references to useful materials on the Internet. It includes short tutorials on basic mathematical topics to help readers refresh their mathematical knowledge. An appendix on Mathematica encourages the reader to use computer-aided algebra to solve problems in mathematical physics. To request a copy of the Solutions Manual, visit: Editorial Reviews From the Publisher "This book gathers together in one place both standard and advanced topics on mathematical methods in physics. As such, it will be of use to both researchers and students in theoretical physics, as well as university-level lecturers who may wish to use it as a textbook. The second edition expands on the set of problems of the first edition, and includes new material on special relativity and chaos. It covers a broad spectrum of topics that will be of enormous use to theoretical physicists." -- Richard J. Szabo, School of Mathematical and Computer Sciences, Heriot-Watt University Meet the Author Wong is a theoretical physicist educated at UCLA and Harvard. He has worked in Copenhagen, Princeton, Oxford, and Saclay (near Paris). He has been at UCLA since 1969. He was a Sloan research Fellow, and is a fellow of the American Physical Society. His main interest is in
New and Published Books – Page 4 Master the tools of MATLAB through hands-on examplesShows How to Solve Math Problems Using MATLAB The mathematical software MATLAB® integrates computation, visualization, and programming to produce a powerful tool for a number of different tasks in mathematics. Focusing on the MATLAB toolboxes... Comprehensive Coverage of the New, Easy-to-Learn C# Although C, C++, Java, and Fortran are well-established programming languages, the relatively new C# is much easier to use for solving complex scientific and engineering problems. Numerical Methods, Algorithms and Tools in C# presents a broad... Brings Readers Up to Speed in This Important and Rapidly Growing Area Supported by many examples in mathematics, physics, economics, engineering, and other disciplines, Essentials of Topology with Applications provides a clear, insightful, and thorough introduction to the basics of modern topology.... Partial Differential Equations, Fourier Series, and Special Functions This book is a text on partial differential equations (PDEs) of mathematical physics and boundary value problems, trigonometric Fourier series, and special functions. This is the core content of many courses in the fields of engineering, physics, mathematics, and applied mathematics. The... Modern Tools to Perform Numerical DifferentiationThe original direct differential quadrature (DQ) method has been known to fail for problems with strong nonlinearity and material discontinuity as well as for problems involving singularity, irregularity, and multiple scales. But now researchers in... Through several case study problems from industrial and scientific research laboratory applications, Mathematical and Experimental Modeling of Physical and Biological Processes provides students with a fundamental understanding of how mathematics is applied to problems in science and engineering.... Taking a conceptual approach to the subject, Concepts in Quantum Mechanics provides complete coverage of both basic and advanced topics. Following in the footsteps of Dirac's classic work Principles of Quantum Mechanics, it explains all themes from first principles. The authors present alternative... Incorporating substantial developments from the last thirty years into one resource, Asymptotics and Borel Summability provides a self-contained introduction to asymptotic analysis with special emphasis on topics not covered in traditional asymptotics books. The author explains basic ideas,... One of the Top Selling Physics Books according to YBP Library Services Suitable for graduate students, experienced researchers, and experts, this book provides a state-of-the-art review of the non-relativistic theory of high-energy ion-atom collisions. Special attention is paid to four-body... Difference Methods for Singular Perturbation Problems focuses on the development of robust difference schemes for wide classes of boundary value problems. It justifies the ε-uniform convergence of these schemes and surveys the latest approaches important for further progress in numerical...
1. DEFINE THE PROBLEM 1.1 UNDERSTAND THE PROBLEM. 1.2 SPECIFY THE DETAILS OF THE PROBLEM. 1.3 WRITE A DESCRIPTION OF THE PROBLEM. 2. VISUALIZE THE PROBLEM AND POSSIBLE SOLUTION METHODS 2.1 DRAW PICTURES OF THE PROBLEM. 2.2 DRAW DIAGRAMS OF THE PROBLEM. 2.3 PLAN POSSIBLE SOLUTION METHODS. 2.3.1 DRAW CONCEPTUAL DIAGRAMS OF POSSIBLE PROCEDURES. 2.3.2 DRAW PICTURES OF EXPECTED RESULTS FROM SOLUTION METHODS. 3. DESCRIBE WHAT KNOWN RESOURCES ARE AVAILABLE TO PRODUCE RESULTS 3.1 LABEL ALL PICTURES AND DIAGRAMS WITH THE KNOWN INFORMATION. 3.2 ASSIGN SYMBOLS TO KNOWN RESOURCES. 3.3 LIST ALL KNOWN CONDITIONS AND CHARACTERISTICS. 4. IDENTIFICATION OF THE RESULTS TO BE FOUND 4.1 DESCRIBE WHAT RESULTS ARE NEEDED. 4.2 DESCRIBE THE UNKNOWNS WHICH NEED TO BE DETERMINED. 4.3 ASSIGN SYMBOLS TO EACH UNKNOWN DESCRIBED. 5. DESCRIBE THE PROCEDURES AVAILABLE TO PRODUCE THE RESULTS FROM RESOURCES 5.1 LIST ALL SET OF RULES (IN SYMBOLIC FORM) WHICH RELATE NEEDED RESULTS AND RESOURCES. 5.2 LIST ALL FORMULAS IN SYMBOLIC FORM WHICH CAN BE USED TO DETERMINE RESULTS FROM RESOURCES. 5.3 LIST ALL EQUATIONS IN SYMBOLIC FORM WHICH RELATE NEEDED RESULTS TO RESOURCES. 6. SYNTHESIS OF A SOLUTION 6.1 USE THE AVAILABLE PROCEDURES TO PRODUCE THE DESIRED RESULTS FROM THE KNOWN RESOURCES. 6.2 REPLACE THE SYMBOLS USED IN THE PROCEDURES WITH ACTUAL VALUES OF KNOWN QUANTITIES. 6.3 DETERMINE THE VALUES OF ANY RESULTS WHICH CAN BE FOUND DIRECTLY BY FOLLOWING THE RULES OR USING THE FORMULAS AND EQUATIONS. 6.4 USE THE RESOURCES AND ANY RESULTS NOW AVAILABLE TO DETERMINE OTHER RESULTS. 6.5 USE THE AVAILABLE PROCEDURES (USING TRIAL AND ERROR WHEN NECESSARY) TO DETERMINE THE REMAINING NEEDED RESULTS FROM THE ALREADY CALCULATED RESULTS AND THE KNOWN RESOURCES. USE ALL THE PROCEDURES UNTIL ALL THE POSSIBLE COMBINATIONS HAVE BEEN TRIED. 7. EVALUATE THE SOLUTION 7.1 IS THE SOLUTION POSSIBLE? 7.2 IS THE SOLUTION REASONABLE? Demonstration of the Use of this Problem Solving Procedure Steps 1 through 5 are the ANALYSIS OF THE PROBLEM. Steps 6 and 7 are the SYNTHESIS OF A SOLUTION. For Example: I. Find the length of the side of a cube shaped block of copper which weighs 49 Newtons.
FAQs General Why should I consider A+ TutorSoft products? A+ TutorSoft, Inc. offers very comprehensive Interactive MATH Curriculum products that are easy to use, self-paced, powerful and low cost. The goal of the A+ TutorSoft is to help students of all ability and grade levels reach their educational potential by offering expert instruction that is engaging, easy to follow and easily accessible at the LOWEST COST. Using a proprietary learning platform that combines voice,visual and text-based instructions, we make learning MATH easy. Centered on the proven methodology of a test-grade-review cycle, our instructional platform delivers personal, highly-effective, and expert instructions. We have been developing our Full-Year Interactive MATH programs for over 7 years based on extensive research into what students and parent-teachers want. We found students want simple and concise multimedia lessons, interactive problem-solving and step-by-step explanations to every problem and parent-teachers want the tools that will take the burden of day-to-day teaching away from them and allow them to focus on the specific area where students need additional help. We understand that learning and teaching MATH is not easy, so we do all we can to take the stress out so it is more enjoyable for everyone. A+ TutorSoft is working on additional high school grade levels and plans to offer K-12 Math curriculum soon. I am an Apple MAC user, can I use A+ TutorSoft Math curriculum for my homeschool journey? Yes. A+ TutorSoft offers Homeschool Math Online edition which is compatible with most major browsers including Safari for MAC. All you need is a high-speed internet connection to use Homeschool Math Online after purchase. Does A+ TutorSoft offer book products? If so, what book products are available? Yes. A+ TutorSoft offers several book products. Some of the titles available from A+ TutorSoft are: A+ TutorSoft offers Homeschool MATH Online Edition that includes worksheets and exams that can be completed online and graded automatically. However, The CD software does not offer this functionality. A+ Interactive Math CD software is a complete and highly effective MATH curriculum which allows parents to remain in control while alleviating any burden of teaching MATH concepts. Parents are NOT required to have mastery of MATH, but are able to maintain involvement at whatever level they deem necessary. All you need is a computer with a Windows Operating System and about 250MB hard-disk space to use the CD-based software. If you are using an Online MATH curriculum, all you need is a computer (Windows PC or Mac) with a high-speed internet connection. How can I get help from the A+ TutorSoft? A+ TutorSoft provides detailed user guides for all their products. You can also contact A+ TutorSoft at anytime by sending an email or using a phone listed on their Contact Us page. Are the A+ TutorSoft products suitable for any states in the USA? A+ TutorSoft has worked very hard to provide most complete and comprehensive course contents to meet and exceed all state requirements. Does A+ TutorSoft offer volume purchase discount? Yes. A+ TutorSoft does offer a price break for volume purchase. The amount of discount depends upon the number of items to be purchased. Please contact us sales@aplustutorsoft.com for more information. For example, if you are part of a large co-op or support group and your group is participating in our "Group Discount Program", you will get 25% off on all software purchases at any time. If your group is not participating at this time, please have your group leader contact us at info@aplustutorsoft.com.com to setup a group discount for your group Can I see a demo of the product before I buy it? Yes. Please see the View Demo link on the A+ TutorSoft site to view a full product demonstration of each product line. You may download a trial software for your Windows PC as well as sign up for a free 1-month access to Homeschool MATH Online. What FREEBIES does A+ TutorSoft offer? A+ TutorSoft offers many daily FREEBIES such as, FREE MATH Placement Tests Free 1-month Online MATH Worksheets Exams Multimedia Lessons And even FREE Full MATH Curriculum CD (limited time promotional offer in the form of giveaways). Can I install the A+ Interactive Homeschool Math Curriculum software on more than one computer? Yes, as long as it is intended for use by the members of the family in the same household. Under the license agreement, you are NOT permitted to install the software for any other use including commercial use. Please see the "Terms and Conditions" of the license agreement for details. Why should I consider upgrading to Homeschool MATH Online? Homeschool MATH Online offers many more valuable features in addition to those included with the CD software. See Product Feature Comparison for more information. How can I get updates from the A+ TutorSoft? If you are using a CD-based software, A+ TutorSoft will make the updates available on the website when appropriate. If you are using an online MATH curriculum, you DO NOT need to do anything to receive any updates. The A+ TutorSoft maintains the online portfolio with the latest updates. All the updates are made directly to our products on the web. You will automatically see the updates when you launch your application. I noticed some errors in the multimedia presentation, what should I do? The additional FREE online homework help is currently not available from the A+ TutorSoft but the plans are in place and this FREE online homework help will be available to all student subscribers in a very near future. How much does the homework help cost? The online homework help during pre-designated hours shall be FREEto all subscribers once available in a very near future. Is the online tutoring available from the A+ TutorSoft? The A+ TutorSoft is developing plans to offer user paid online one-on-one tutoring as well as group tutoring sessions in a very near future. How does the online tutoring work? Once available, students shall be able to schedule time for the tutoring. Students shall be allowed to join the live tutor online at a scheduled time. How much does the Online tutoring cost? Please visit us at a later time for the pricing information on private online tutoring.
12 coins problem - Frans Faase A classic math puzzle: given a balance scale and 12 coins, one of which is counterfeit and weighs less or more than the other coins, determine the counterfeit in 3 weightings, and tell if it is heavier or lighter. Extensions to other cases and the general ...more>> alt.math.undergrad - Math Forum An unmoderated discussion forum for issues and problems pertaining to college undergraduate mathematics. Read and search archived messages; and register to post to the discussions. ...more>> Arbeitsgruppe Bachem/Schrader - University of Köln A working group of the Center for Parallel Computing (ZPR) at Köln. Site includes a list of members and contact address; informative write-ups on its projects, some in English. Topics include: Basic Research (meaning "pure" as opposed to "applied"); ...more>> Brendan McKay Software includes nauty, a program for computing automorphism groups of graphs and digraphs, which can also produce a canonical labelling; and plantri, a program for generating planar triangulations. Also, skeptical treatment of claims made of miraculous ...more>> CS22: Discrete Math - Brown University An introduction to discrete math with a focus on proof, logic, proof by induction, cryptography and networks of processors: lessons, homework, solutions, and information. "Discrete mathematics" refers to the distinction between discrete sets (for example,David Sumner's Home Page - David Sumner Study guides, exams, quizzes, problem sets, exam review materials, utilities, programs and simulations, syllabi, and other materials for courses such as calculus, sequences and series, graph theory, number theory and cryptography, and probability. The ...more>> Developing Algebraic Thinking - Suzanne Alejandre Teacher lesson plan and student kinesthetic activities on the Traffic Jam activity and applet, as originally published in the inaugural (Fall, 2002) issue of ON-Math, an electronic journal of the National Council of Teachers of Mathematics (NCTM). ...more>> A Dice Game - Doug Ensley, Shippensburg University In this game, two players roll dice repeatedly taking note of who has the higher roll each time. The original number of dice for each person and the number of rolls are set by the user. At the end, the percentage of wins for each player is displayed. ...more>> discretemath - Math Forum A discussion group for subject matter concerning teaching and researching of discrete mathematics at all levels. It began as a closed list for the researchers and educators who participated in the Rutgers University Discrete Math and Theoretical Computer ...more>> Discrete Math Problem of the Week (PoW) - Math Forum Discrete math problems from a variety of sources, including textbooks, math contests, NCTM books, and puzzle books, and real-life situations, designed to reflect different levels of difficulty. From 1999 until 2002, this service challenged students with ...more>> Division by Zero - Dave Richeson A blog about "math, puzzles, teaching, and academic technology." Posts, which date back to September of 2008 and sometimes introduce original applets, have included "Volumes of n-dimensional balls," "Albrecht Dürer's ruler and compass constructions," ...more>> Drawing Tools - Shai Duvdevani A growing group of .NET C# programs intended to make life easier for highschool and university students studying subjects such as math, computers and electronics. Each of these programs features saving and loading, so that sharing a drawing of logical ...more>> Elementary Computer Mathematics - Kenneth R. Koehler An introduction to the mathematics used in the design of computer and network hardware and software. This hypertextbook's goal is to prepare the student for further coursework in such areas as hardware architecture, operating systems internals, application ...more>> Elsevier Science "Information Provider to the World." Elsevier's mission is "to advance science, technology and medical science by fulfilling, on a sound commercial basis, the communication needs specific to the international community of scientists, engineers and associated ...more>> Emaths.Info - Vinod Sebastian Math tools, formulas, tutorials, videos, tables, and "curios," such as the unusual properties of 153, 1729, and 2519. See in particular Emaths' interactive games, which include the N queens problem, Towers of Hanoi, and partition magic, which finds a ...more>>
Browse Results Modify Your Results Welcome to Consumer Mathematics. This book includes many of the math skills that you will need now and later in life. Why do you need these skills? Think about the world of mathematics around you. When you buy something, you use math to count money. When you measure something, you use numbers to calculate units of measurement. Buying food, paying taxes, banking, and managing a household all require at least some sort of math. This book on Consumer Mathematics will be very useful for day-to-day dealings. The chapters included are: Earning Money, Buying Food, Shopping for Clothes, Managing a Household, Buying and Maintaining a Car, Working with Food, Improving your Home, Traveling, Budgeting your Money, Banking and Investing, Paying Taxes, and Preparing for Careers Plan a business-oriented curriculum for your students with this full-color, easy-to-read text that focuses on the skills students need on the job. Math for the World of Work covers critical skills like whole numbers, fractions, decimals, averages, estimating, measurements, and ratios. Each skill is introduced in a cross-curricular context that helps students learn about the business world. Lessons are reinforced with problem-solving activities, exercises, and review questions to give students plenty of practice and solidify their understanding of new skills. And features like Application Activities and Technology Connections ensure that students understand how to apply the skills they acquire
If you provide us with a few extra details when you register you will receive a free publication and become an Associate of ATM. In your basket: Nothing yet Making Algebra Come Alive How the publisher describes it: "Each activity is presented as a reproducible student investigation. It is followed by guidelines and notes for the teacher. Each activity is keyed to the National Council of Teachers of Mathematics (NCTM) Standards, Revised. This link to the NCTM standards allows teachers to facilitate linking classroom activities to specific state and school district content standards." Review by Peter Hall In brief: This is a very interesting book and one that can only help our battle to make algebra come alive and help our students see the useful and interesting problems that algebra can help us to deal with. "Well-written and easy to follow" Making Algebra Come Alive is often a challenge for us - many of our students don't seem to get the point, and this lack of understanding seems to last quite a long time for many of our students - I'm still amazed how many year 12 students have never really grasped what we believe to be quite fundamental. The activities have a student version - asking structured questions to lead the students into interesting areas of mathematics. Topics range from Equations, Probability, Problem Solving and Number Theory. The worksheets are clear to understand and lead the student nicely through the lesson. As an example, one such worksheet helps the student to better understand the difficulties of averages - using not only the average speed problem (50 miles per hour on the way out, 25 miles per hour on the way home... so why is the average speed not 25 miles per hour?) but also includes an example from test scores ( 90% on three test and 60% on the fourth - and the average clearly shouldn't be 75%?). This leads neatly onto consideration of weighted means. The teachers notes are well-written and easy to follow yet explain the complex problems very well. Ideas are given to extend the students' understanding. This is a very interesting book and one that can only help our battle to make algebra come alive and help our students see the useful and interesting problems that algebra can help us to deal with.
Book DescriptionEditorial Reviews About the Author Allan G. Bluman is Professor of Mathematics at Community College of Allegheny County, near Pittsburgh. For the McKeesport and New Kensington Campuses of Pennsylvania State University, he has taught teacher-certification and graduate education statistics courses. Prior to his college teaching, he taught mathematics at a junior high school. Professor Bluman received his B.S. from California State College in California, Penn.; his M.Ed. from the University of Pittsburgh; and, in 1971, his Ed.D., also from the University of Pittsburgh. His major field of study was mathematics education. In addition to Elementary Statistics: A Step by Step Approach, Third Edition, and Elementary Statistics: A Brief Version, the author has published several professional articles and the Modern Math Fun Book (Cuisenaire Publishing Company). He has spoken and presided at national and local mathematics conferences and has served as newsletter editor for the Pennsylvania State Mathematics Association of Two-Year Colleges. He is a member of the American Statistical Association, the National Council of Teachers of Mathematics, and the Mathematics Council of Western Pennsylvania. Al Bluman is married and has two children. His hobbies include writing, bicycling, and swimming. Be aware that there are at least two versions of this book labeled as an eighth edition. The version described on this page ISBN-10: 0073386103 / ISBN-13: 978-0077460396, the version I ordered (used). Then there is the version I received ISBN-10: 0073386103 / ISBN-13: 978-0073386102, it is unclear if it is supposed to have a CD and Formula Card. The version I received had it, but another reviewer of that version did not receive it. Beware that if you receive the latter version the Amazon sell back price is about half that of the former. Be sure to check the ISBN to make sure you receive the book you ordered. I wish I had! As for the book itself, it seemed fine for the class taken. The CD was not really very useful, but you must buy what is required for the class. Book itself is thorough though the CD did not work whatsoever on my computer.(It may work on yours?) Formula card was handy, but I could have easily done without it. My advice would be to double check ISBN on your receipt to the book itself immediately when you receive it, otherwise you will not be able to trade it in. There are identical books with different ISBN's out there. This book is serving me well on statistics right now. There are a few flaws in this book that the author needs to update on and that is the answer section because it is such a big deal going back through your notes, professor and so forth. The book came really fast, which was great because i didn't fall behind in class. It came in perfect condition, no pages missing or anything. One down side was that it did not come with the Data DC or the Formula Sheet, I didn't mind that it didn't come with the CD but I was really disappointed that there was no formula sheet because I need it for tests in my class. If it wasn't for that this book would have gotten 5 stars instead of 4. Before purchasing make sure it contains formula sheet, if not I was able to find it on google for free. Other than that the book is great and the way it is divided and set up is easy to follow, each lesson is explained perfectly and straight to the point.
LogarithmsIn this chapter you must be able to(i)understand the relationship between logarithms and indices, and usethe laws of logarithms (excluding change of base)(ii)understand the definition and properties of e x and ln x, including therelationship as inverse functions and their graphsRelationship between log and indicesLet
Editorial Reviews Review "This book is an excellent way to learn quickly how to use MATLAB.The most significant changes in this edition include a new chapter on vectorized code and manipulating vectors, concepts used in image processing, modified and new end-of-chapter exercises, and the use of MATLAB version R2011a."--Electrical Insulation Magazine, January 2013, Vol. 29, No. 1, page 66 "This book is an excellent way to learn quickly how to use MATLAB.Anyone who wants to learn the basis of MATLAB quickly should own this book."--IEEE Electrical Insulation Magazine, page 66 "In and updates to reflect current features and functions of the current release of MATLAB."--Lunar and Planetary Information "Assuming no knowledge of programming, this book presents both programming concepts and MATLAB's built-n functions, providing a perfect platform for exploiting its extensive capabilities for tackling engineering problems. The book starts with programming concepts such as variables, assignments, input/output, and selection statements, moves onto loops, and then solves problems using both the 'programming concepts' and the 'power of MATLAB' side by side. In, and updates to reflect current features and functions of the current release of MATLAB."--Lunar and Planetary Information Bulletin, December 2011, Issue 127, page 46 "This is the perfect book for anyone wanted to acquire a secure understanding of MATLAB fundaments and master its language. Many engineers and scientists now use MATLAB and Simulink to solve real-world problems. With the help of this book, they will be able to exploit the full power of MATLAB much sooner than they would using the online manuals, and be able to solve real problems much more quickly."--IEEE Electrical Insulation Magazine, page 70 About the Author Boston University. PhD Boston University Department of Mechanical Engineering at Boston University, and Associate Chair for the Manufacturing Engineering undergraduate program within the department. She has been the course coordinator for the Engineering Computation courses at Boston University for over twenty years, and has taught a variety of programming courses using many different languages and software packages. In the case of this product, there is truth in advertising. The book itself assumes no knowledge of MATLAB with almost no math beyond some basic high school math. The book was developed for incoming freshman at Boston University by a longtime educational coordinator. The author put considerable work into this book, and for someone who wants to learn MATLAB on their own, this is a pretty good choice. The examples are simple and easy to follow with the content suitable even for aggressive high school students. Matlab no longer needs any sort of hyping, it is used in many disciplines ranging from engineering to economics to education, although engineers are the true power users. As an experienced user, I most likely to use this book as a reference when I simply forget one of the many Matlab constructs. As a reference, the material is quite extensive and diverse but still does not get too aggressive in any of the content. In a nutshell, the book will 1. Get you familiar with the MATLAB command set 2. Get you familiar with the MATLAB user interface 3. Teach you how to import data, manipulate the data based on the baseline MATLAB instruction set, and generate decent but often clunky looking plots (many people that I know will often port the data out to a better plotting package such as excel) 4. Develop a collection of commands (call .m files) that perform an extended sequence of commands and can be run from session to session The MATLAB program is not included in the book and can be quite costly, so if you don't have a copy of MATLAB, you might want to check out its affordability first. Also, there is no companion disk with the book meaning that you have to do all the typing of the examples in the book. This is more of a luxury than a necessity (in my opinion). Why only 4 stars? Quite honestly, the book was a bit too basic for me. The book did not deal with one very important subject which is interfacing with .C programs. This has become commonplace in the workforce and although it doesn't fit nicely with an intro book, some material should have been included on this important subject. In addition, some of the examples were almost too simplistic resulting in cases where nothing really significant is shown. Plotting for the most part was kept to a basic level and as a result, most of the plots in the book look basic. These are points that are worth downgrading the book one star, but not enough to really detract from its overall appeal as an introductory or good reference book. If you're looking for a book that is either a good introduction with no assumed prior knowledge or simply a basic reference, this book is highly recommended.Read more › MATLAB is one of the most advanced mathematical and computational software environments that are currently available. In my line of work I have primarily used Mathematica, which is a bit better suited for symbolic manipulation rather than numerical and statistical analysis and modeling. Recently I've ventured into some numerical work, and have decided to learn how to use MATLAB. In that regard I am happy to report that Stormy Attaway's "MATLAB - A Practical Introduction To Programming And Problem Solving" is an excellent pedagogical resource. Some of the overarching features of this book are: * Hybrid approach that combines both the programming techniques as well as the exposition of MATLAB's own functions. * Systematic, step-by-step approach building concepts throughout the book. * Exposition of MATLAB's ability to work with large and complex files and other inputs. * Introduction of some advanced programming concepts, such as string manipulation, data structures, recursion, anonymous functions, sorting, searching, and indexing. * The book also has a short introduction to several key mathematical and problem-solving concepts, such as statistical functions, sets of linear algebraic equations, the use of complex numbers, and some calculus. Some pedagogical features: * Quick Question! - questions that are posed throughout the book and immediately answered. * Practice problems are given throughout the chapter * Introduced problems are solved using both The Programming Concept and The Efficient Method. The book comes with a companion website that makes available several MATLAB files and programs which can be used to solve the problems throughout the book. The faculty also have the access to additional course material, including solutions manual, electronic figures from the text, and downloadable files for all examples in the text. Each chapter starts with a list of key-terms. They can be a useful bare-bones guide to the content of each chapter, as well as a study reference. The presentation of the material is very pedagogical and it was clearly written with the aim of guiding the students and helping them absorb the information as painlessly as possible. The chapters end with a series of exercises. These can be used for homework or further study and reinforcement of the material. The exercises vary in difficulty, from the straightforward application of the already worked-out problems in the text, to the more challenging programming assignments. Some of the latter could serve as a basis for a term project. This book makes a great textbook for a wide variety of introductory computational classes. It can be used in engineering, statistics, and sciences, as well as for more mathematically advanced modeling in other disciplines. As I've come to discover, this book can also be used for self-study, especially if you are already familiar with most of the mathematical and programming concepts.Read more › First a disclaimer: I chose to receive this textbook to review from the Vine program, meaning I got it for free. I am an Electrical Engineer and I like to have references for the different languages I use at work...not having one for MATLAB, I thought this would be nice to try. Here's my review: This book is exactly what it claims to be: an introduction to MATLAB. All in all, it appears to be a very well written textbook (I already know MATLAB so I can't say I tried learning with this book, but I did browse through it and read some sections in detail and it was a very good reminder and seemed easy to follow and understand). The book does a fantastic job of describing the different functions and terms it covers. It also is filled with useful smatterings of actual MATLAB syntax and code including at times alternate methods for achieving the same output. Code examples are good and text explaining them are very easy to read and follow. Well written for what is essentially a programming book! The table of contents is well organized and descriptive, making it easy to skip around the book looking for specific topics. Index is decent...could stand a tad more detail, but acceptable. The preface makes a good point - the book seeks to explain both the use of functions and the programming concepts. I can't say it's completely unique to approach MATLAB this way, but it is, in my mind, the preferable way to do it. Using functions alone doesn't leave you much flexibility when you are faced with something more complex and need to actually write useful programs or something not directly correlating to a function. But not knowing the functions really cripples your productivity. The book also touches briefly on some of the more advanced concepts in MATLAB (even 3D plots, animation, sound and image processing). Not enough to really use these super effectively without another reference, but enough to try at least simple versions and to know that it exists as an option, which for an intro book is quite acceptable and nice that it bothers at all. I do like the practice features in the text - most of them basically have you pen and paper what you think the output of things will be and then go into MATLAB to check your answers. It seems a little trivial to have to be solving math equations by hand until you realize it's a great way to make sure that you both understand the math and the MATLAB. If they don't agree you did one or the other wrong! I liked this idea quite a lot for both students and myself : Good review of both language and math. As for the problems in the text, reading them, they seem useful. Some are very easy seeeming and some really do require you to think (the later chapters basically make you write a complete program). I didn't try them honestly, but at least they are clear - I don't have too many questions understanding what they want which is very good for a textbook. Without an answer manual, these aren't as useful to me though since I could do the problem, but not really check my work unless I did it by hand as well (which is why I think the set-up/suggestion in the book for how to do the practice problems is so great). I did knock it down to four stars for a few things though that made it a little less useful as a reference in my mind (and in my mind any good textbook should be judged this way...even if you buy it for class, you want to be able to turn to it years later as a reference). First - I understand MATLAB has a VERY good help feature that explains almost any function. But that's only really helpful if you know to bother looking for the function in the first place. One of the most useful things any programming book can have for me is a library/list of all the functions with a brief explanation of any variables. Then when I'm programming I can scan the list looking for, say, anything with "matrix" in it if I know I'm going to be using matrixes. Sometimes just seeing the name of a function is really useful to me to let me know that "hey, the language has a function for this!" This book doesn't have that. A great deal of the functions are described in the text, but there is no list that I've found in it. If you find one, point it out to me in a comment please, but flipping through it, if there is one I totally overlooked it). In some of the sections, additional functions are mentioned beyond those that are explicitly explained, which is good, but the variables and syntax are not explained which is also too bad...although with MATLAB's help I could figure it out if I need to. Second - In my courses (I have a Master's in Robotic Controls) I had to use a lot of toolboxes and do in work as well. Toolboxes are basically the MATLAB version of additional software add-ons (kind of like libraries in other languages) which give you additional functions you can call. The basic student edition of MATLAB software doesn't come with any toolboxes (at least it didn't used to) and toolboxes are expensive, but I still find it quite unfortunate that I couldn't find any mention of toolboxes in this book. It would be really nice to get a list of the toolboxes available for MATLAB and a brief description of what each covers (a paragraph or two). In my mind an intro book is a great place to put info like this...it tells you were to turn next if you need to head off in some more detailed direction after you grab the basics. I'll update the review if I discover more...at this point the reading is as described - looking at the index and table of contents, browse of most most of it, and in depth reading of a few sections (notably the preface, "is" functions, scripts, loops, advanced tops, maxix representation, and sound and image processing)Read more ›
With CD! Shows definite wear, and perhaps considerable marking on inside. 100% Money Back Guarantee. Shipped to over one million happy customers. Your purchase benefits world ...literacy!Stewart's remarkable new calculus text signals the meeting of two schools of thought at one historic junction. Calculus: Concepts and Contexts, Single Variable maintains mathematical integrity as it skillfully merges the best of traditional calculus with the best of the reform movement. Written from the ground up, this all-new text takes students beyond memorization and helps them to develop mathematical thinking skills. In Calculus: Concepts and Contexts, Single Variable, this well-respected author emphasizes conceptual understanding--motivating students with real world applications and stressing the Rule of Four in numerical, visual, algebraic, and verbal interpretations. All concepts are presented in the classic Stewart style: with simplicity, character, and attention to detail. In addition to his clear exposition, Stewart also creates well thought-out problems and exercises. The definitions are precise and the problems create an ideal balance between conceptual understanding and algebraic 14 of 15 Customer Reviews Anonymous Posted October 15, 2002 Disappointed teacher I have been teaching math on the college level for over 20 yrs. I am disappointed to say that there are much better texts that should be used in a classroom setting. 1 out of 1 people found this review helpful. Was this review helpful? YesNoThank you for your feedback.Report this reviewThank you, this review has been flagged. Anonymous Posted September 7, 2002 Calculus Textbooks are supposed to explain concepts as well as give examples. This book approaches learning by example, but along with that should come explanation. This book is too expensive for what it dosen't deliver, knowledge. 1 out of 1 people found this review helpful. Was this review helpful? YesNoThank you for your feedback.Report this reviewThank you, this review has been flagged. Anonymous Posted July 15, 2002 There has to be better This text did a very good job of explaining the material in the early chapters, but once you reach the later chapters that include multivariable calculus it goes downhill. The examples to some lessons don't help explain anything. Most of the lessons in the last 5 chapters are only good for providing practice problems. You must have a good teacher to understand the material though. 1 out of 1 people found this review helpful. Was this review helpful? YesNoThank you for your feedback.Report this reviewThank you, this review has been flagged. Anonymous Posted November 7, 2001 Needs Improvement His book is not real clear and if one spends time doing most of the problems listed for each section, they will find that he does not present a clear explanation on how to solve most of the higher numbered problems. He really needs to work on his presentation. 1 out of 1 people found this review helpful. Was this review helpful? YesNoThank you for your feedback.Report this reviewThank you, this review has been flagged. Anonymous Posted July 8, 2002 Good enough This is one of the better written text books that i have seen in a very long time, and i think it is very good, and very read-able. I am a math major and i hope that i will be able to find more books like it because it is wonderful. High school they were aweful and didn't explain anything and yours is given with many examples and is kinda easy to pick up on with the steps that you use. Just be sure next time to have examples for all of your practice problems, and don't assume that just because they are in calculus class they know what was supposed to be learned before. Maybe just add a little something from before in some of the exericises that you work the problem out so that one can recoginize and see what you are actually starting from. But besides that it is a class you can teach yourself with your book!! Keep it up and I can't wait for the next one. Was this review helpful? YesNoThank you for your feedback.Report this reviewThank you, this review has been flagged. Anonymous Posted September 30, 2001 good book, cant look at it!! i have to agree with the archemides... its a good book, but i cant stand the very very dull, and plain explanations that are given here!! but it def. teaches wat it should with explanations, and good figues.... Was this review helpful? YesNoThank you for your feedback.Report this reviewThank you, this review has been flagged. Anonymous Posted September 22, 2001 THIS IS A GREAT BOOK! I use this book for my Multivariate Calculus class at Stuyvesant High School in NYC. It is a great book. Although for this class, we only use the second portion of the book, this year, my school has ordered more copies for the Calculus BC students to use the first portion of the book that does not deal with Multivariabe. 0 out of 1 people found this review helpful. Was this review helpful? YesNoThank you for your feedback.Report this reviewThank you, this review has been flagged. Anonymous Posted December 11, 2000 Nasty Calculus with 0 stars I HATE CALCULUS!!!!!!!!! IT IS THE WORST SUBJECT IN THE WORLD!!! EVEN THOUGH THIS IS A GOOD BOOK, THE SUBJECT IS SO HORRID THAT THE BOOK BECOMES HORRIBLE TOO. 0 out of 1 people found this review helpful. Was this review helpful? YesNoThank you for your feedback.Report this reviewThank you, this review has been flagged. Anonymous Posted December 15, 2000 A very excellent textbook I would like all of you to enjoy the excitements in discovering calculus when you read this excellent calculus textbook. I am using it right now and I am really amazed how wonderful the author's explanations about the concepts.This book hads a tons of great figures and lots of examples to illustrate the concept. I would like all of you to buy this book and enjoy the beautiful of this subject Was this review helpful? YesNoThank you for your feedback.Report this reviewThank you, this review has been flagged.
More About This Textbook Overview In this charming memoir, a renowned mathematician and winner of the American Book Award traces his career in mathematics from early lessons in horse racing and the realities of life to his adventures on the lecture circuit. A thought-provoking mix of autobiography, history, and insights into the role of mathematics in everyday life, this highly entertaining book will appeal to all readers. Editorial Reviews Booknews Retired from Brown University, mathematician and author Davis reflects on his life and profession in interwoven anecdotes concentrating on the role mathematics has played in the development of modern culture, and how modern technology has affected the goals and teachings of mathematics
Edexcel AS and A Level Modular Mathematics Core Mathematics 1 C1 - Edexcel AS and A Level Modular Mathematics Edexcel and A Level Modular Mathematics C1 features: *Student-friendly worked examples and solutions, leading up to a wealth of practice questions. *Sample exam papers for thorough exam preparation. *Regular review sections consolidate learning. *Opportunities for stretch and challenge presented throughout the course. *'Escalator section' to step up from GCSE. PLUS Free LiveText CD-ROM, containing Solutionbank and Exam Cafe to support, motivate and inspire students to reach their potential for exam success. *Solutionbank contains fully worked solutions with hints and tips for every question in the Student Books. *Exam Cafe includes a revision planner and checklist as well as a fully worked examination-style paper with examiner commentary. Product details It's Okay This book is probably good in a classroom environment as the explanations given are a bit scant, and they try and make up for this with copious examples but it doesn't quite work. You might want to supplement this with another book with fuller explanations. 15 March 2012 It's Effective For Students, really easy way to learn as long as you get your head round certain topics. For teachers, Good questions and assists with detailed explanations. 23 September 2010
Registration is now open for five online numeracy courses for adult educators: Number Sense: Teaching About Parts and Wholes, Geometry: Teaching About Shapes and Their Measures, Data: Interpreting Statistical Representations, Algebra: Introducing Algebraic Reasoning and Introduction to College Transition Math. The courses are available at Number Sense: Teaching About Parts and Wholes Teaching students how to estimate, do mental math, and use calculators will help them to better understand how to use numbers. This course focuses on how to help adult students answer key questions: When is it necessary to have an exact answer, and when is an estimate sufficient? When calculation is necessary, which tool is appropriate to use? This course examines how students develop and apply number sense and provides lots of teaching strategies and activities that you can use right away. Adult basic education students need foundational geometry and measurement skills not only to succeed in GED math, but also in the workplace. In this course, you will explore key topics in geometry, such as area, perimeter, and volume, and their importance in everyday life. You'll look at numerous instructional activities for teaching about angles, spatial relationships, similarity, and figure transformations on a coordinate graph system. Data, or numerical information, can be described, represented, analyzed, and interpreted in various ways for various purposes. This course looks at some common uses (and misuses) of data. Learn about the measures of central tendency statistics, graphs, and probability. Through the course readings, activities, and discussions, you'll review basic concepts and explore strategies for introducing and teaching these concepts to your adult students. Research suggests that math topics, including algebra, should be taught at all levels, not just when a student is ready for GED preparation. In this course, you'll learn how to introduce algebraic reasoning to your students, and you'll experiment with strategies for teaching numeric patterns, relationships, and functions based on real-life situations. You'll also explore strategies to help students model quantitative relationships using graphs, tables, words, and equations. Through the readings and activities in this course, you will reflect on your own and your students' math backgrounds, examine and experience the college placement test your students take, try out math activities and exercises you can use in your classrooms, and explore the math knowledge and skills you will want to present to your own college transition students
More About This Textbook Overview In 1821, Augustin-Louis Cauchy (1789-1857) published a textbook, the Cours d'analyse, to accompany his course in analysis at the Ecole Polytechnique. It is one of the most influential mathematics books ever written. Not only did Cauchy provide a workable definition of limits and a means to make them the basis of a rigorous theory of calculus, but he also revitalized the idea that all mathematics could be set on such rigorous foundations. Today, the quality of a work of mathematics is judged in part on the quality of its rigor, and this standard is largely due to the transformation brought about by Cauchy and the Cours d'analyse. For this translation, the authors have also added commentary, notes, references, and an index. Editorial Reviews From the Publisher From the reviews: "The book under review comes equipped with a well-written Translator's Preface, full of interesting and relevant historical data, placing Cauchy's work in the present connection in the proper historical context. … Cauchy's Cours d'analyse, An Annotated Translation is a major contribution to mathematical historical scholarship, and it is most welcome indeed to have occasion to examine the infancy of a part of modern analysis, to recognize familiar things in archaic and even arcane phrasings … and, through it all, to witness a grandmaster in action." (Michael Berg, The Mathematical Association of America, November, 2009) "Bradley (Adelphi Univ.) and Sandifer (Western Connecticut State Univ.) have written an annotated, indexed translation of Cauchy's classic textbook from 1821. The work's most interested readers will probably be students and researchers of the history and philosophy of mathematics education, and education in general. … it will be valuable for specialized historical collections. Summing Up: Essential. … academic history of mathematics education and history of science collections, lower-division undergraduates and above." (M. Bona, Choice, Vol. 47 (6), February, 2010) "The majority of mathematical activity now takes place in English … so this translation is especially welcome. … It is a mathematical delight to read through this book. … Cauchy carefully built the subject up from the most elementary ideas in algebra and arithmetic. … Readers of this review should encourage their libraries to get this book, and anyone interested in the history of mathematical analysis will want to own a copy." (Judith V. Grabiner, BSHM Bulletin, Vol. 26, 2011) Table of Contents Translators' Introduction.- Cauchy's Introduction.- Preliminaries.- First Part: Algebraic Analysis.- On Real Functions.- On Quantities that are Infinitely Small or Infinitely Large, and on the Continuity of Functions.- On Symmetric Functions and Alternating Functions.- Determination of Integer Functions.- Determination of continuous functions of a single variable that satisfy certain conditions.- On convergent and divergent (real) series.- On imaginary expressions and their moduli.- On imaginary functions and variables.- On convergent and divergent imaginary series.- On real or imaginary roots of algebraic equations for which the first member is a rational and integer of one variable.- Decomposition of rational fractions.- On recursive series.- Notes on Algebraic
Differential Geometry and Its Applications By John Oprea Differential geometry has a wide range of applications, going far beyond strictly mathematical pursuits to include architecture, engineering, and just about every scientific discipline. John Oprea's second edition of Differential Geometry and Its Applications illuminates a wide range of ideas that can be beneficial to students majoring not only in mathematics but also in other fields. The textbook touches on many different mathematical concepts, including aspects of linear algebra, the Gauss-Bonnet Theorem, and geodesics. It also encourages students to visualize and experiment with the ideas they are studying through their use of the computer program Maple. This allows students to develop a better understanding of the mathematics involved in differential geometry. About the Author John Oprea was born in Cleveland, Ohio and was educated at Case Western Reserve University and at Ohio State University. He received his PhD at OSU in 1982 and, after a post-doc at Purdue University, he began his tenure at Cleveland State in 1985. Oprea is a member of the Mathematical Association of America and the American Mathematical Society. He is an Associate Editor of the Journal of Geometry and Symmetry in Physics. In 1996, Oprea was awarded the MAA's Lester R. ford award for his Monthly article, "Geometry and the Foucault Pendulum." Besides various journal articles on topology and geometry, he is also the author of The Mathematics of Soap Films (AMS Student Math Library, volume 10), Symplectic Manifolds with no Kähler Structure (with A. Tralle, Springer Lecture Notes in Mathematics, volume 166). Lusternik-Schnirelmann Category (with O. Cornea, G. Lupton and D. Tanré, AMS Mathematical Surveys and Monographs, volume 103) and the forthcoming Algebraic Models in Geometry (with Y. Felix and D. Tanré, for Oxford University Press). MAA Review John Oprea begins Differential Geometry and Its Applications with the notion that differential geometry is the natural next course in the undergraduate mathematics sequence after linear algebra. He argues that once students have studied some multivariable calculus and linear algebra, a differential geometry course provides an attractive transition to more advanced abstract or applied courses. His thoughtful presentation in this book makes an excellent case for this. As he says, the natural progression of concepts in differential geometry allows the student to progress gradually from calculator to thinker. This edition of the text is over a hundred pages longer than the first edition. Evidently Oprea has incorporated many suggestions from those who have taught from the text. There is a good deal to like about this book: the writing is lucid, drawings and diagrams are plentiful and carefully done, and the author conveys a contagious sense of enthusiasm for his subject. Continued...
97800730160 Algebra (hardcover) with MathZone Miller/O'Neill Beginning Algebra is an insightful text written by instructors who have first-hand experience with students of developmental mathematics. The authors have placed an emphasis on graphing, by including special sections called, "Connections to Graphing" at the end of Chapters 1-5, before the formal presentation of Graphing appears in Chapter 6. The "Connections to Graphing" sections may be considered optional for those instructors who do not prefer an early introduction to graphing. For those who do prefer graphing early, instructors can use the "Connections to Graphing" sections together where they prefer to introduce graphing. A section on geometry appears in "Chapter R" for instructors who look for such content in Beginning Algebra. Applications that incorporate geometric concepts may also be found throughout the text. Chapter R also contains a section on study skills. This section provides easy to digest tips (in list format) for course success. The authors have crafted the exercise sets with the idea of infusing review. In each set of practice exercises, instructors will find a set of exercises that help students to review concepts previously learned, and in this way, students will retain more of what they have learned. The exercise sets also contain "translation" exercises which provide students with an opportunity to convert from English phrases to mathematical symbols and from mathematical symbols to English phrases, thus helping students to strengthen their command of mathematical language. Moreover, the applications found in the exercise sets are based on real-world data, which helps to promote students' interest in mathematics, and in turn, may serve to motivate and engage them more effectively. Other features include mid-chapter reviews and classroom activities. The classroom activities are of special value, in that through their use, students may begin to take greater ownership over their learning. The classroom activities were designed to be quick activities students could perform in class (either individually, or collaboratively in groups). In short, the Miller/O'Neill Beginning Algebra text offers enriching applications, a high level of readability, and excellent opportunities for students to become actively engaged in their exploration
052133196val Methods for Systems of Equations (Encyclopedia of Mathematics and its Applications, Vol. 37) An interval is a natural way of specifying a number that is specified only within certain tolerances. Interval analysis consists of the tools and methods needed to solve linear and nonlinear systems of equations in the presence of data uncertainties. Applications include the sensitivity analysis of solutions of equations depending on parameters, the solution of global nonlinear problems, and the verification of results obtained by finite-precision arithmetic. In this book emphasis is laid on those aspects of the theory which are useful in actual computations. On the other hand, the theory is developed with full mathematical rigour. In order to keep the book self-contained, various results from linear algebra (Perron-Frobenius theory, M- and H- matrices) and analysis (existence of solutions to nonlinear systems) are proved, often from a novel and more general viewpoint. An extensive bibliography
Beginning Pre-Calculus for Game Developers 9781598632910 ISBN: 1598632914 Edition: 1 Pub Date: 2006 Publisher: Course Technology Summary: Beginning Pre-Calculus for Game Developers provides entertaining, hands-on explanations of topics central to calculus as related to game development. It explains the mathematics and programming involved in developing nine computer programming applications furnished with the book's CD-ROM. Begin by working your way through first semester calculus topics and then use your new math skills to create programs that apply e...ach topic. Beginning Pre-Calculus presents math topics in a method that is direct, easy-to-understand, and pertinent to all studies related to calculus math. Flynt, John P. is the author of Beginning Pre-Calculus for Game Developers, published 2006 under ISBN 9781598632910 and 1598632914. Four hundred fifty two Beginning Pre-Calculus for Game Developers textbooks are available for sale on ValoreBooks.com, one hundred nine used from the cheapest price of $11.65, or buy new starting at $21.85.[read more] Ships From:Secaucus, NJShipping:StandardComments: Successful game programming requires at least a rudimentary understanding of central math topics... [more] Successful game programming requires at least a rudimentary understanding of central math topics. While most books neglect the point-by-point details that are necessary to truly hone these skills, Beginning Pre-Calculus for Game Developers tackles ea. [less] Successful game programming requires at least a rudimentary understanding of central math topics. While most books neglect the point-by-point details that are necessary to tr [more] Successful game programming requires at least a rudimentary understanding of central math topics. While most books neglect the point-by-point details that are necessary to truly hone these skills, Beginning Pre-Calculus for Game Developers tackles ea.[less]
Questions About This Book? The Used copy of this book is not guaranteed to inclue any supplemental materials. Typically, only the book itself is included. Summary Elementary Algebra, 5th Edition, is designed to provide students with the algebra background needed for further college-level mathematics courses. The unifying theme of the text is the development of the skills necessary for solving equations and inqualities, followed by the application of those skills to solving applied problems
Instructor Class Description Calculus I: Origins and Early Developments Develops modern calculus by investigating the questions, problems, and ideas that motivated its discovery and practice. Studies the real number system and functions defined on it, focusing on limits, area and tangent calculations, properties and applications of the derivative, and the notion of continuity. Emphasizes problem-solving and mathematical thinking. Prerequisite: either a minimum grade of 2.5 in B CUSP 123, sufficient score on approved mathematics assessment test, or a minimum score of 2 on either the AB or BC AP Calculus test. Offered: AWSp. Class description First quarter in calculus of functions of a single variable. Emphasizes differential calculus. Emphasizes applications and problem solving using the tools of calculus. We will use the tools of calculus to explores real world examples and problems. Each idea will be represented symbolically, numerically, graphically, and verbally. Student learning goals * Understand limits and be able to apply the formal definition of limits. *Understand what derivatives are. *How to use derivatives. *Techniques of derivation. *Real life application and modeling using derivatives. *How can technology is used to gain a better understanding of derivatives *Understand what derivatives are. *How to use derivatives. *Learn techniques of derivation. *Real life application and modeling using derivatives. General method of instruction Discussion and group discovery – sometimes as a whole class and sometimes in small groups. Participation is essential to the success of this class. Mistakes in class are ABSOLUTELY OK. Regular attendance and participation is highly recommended and will be included in calculation of the final grade! Recommended preparation Success in calculus depends on a large extend on knowledge of algebra, trig, and functions. Prerequisite: 2.5 or above in B CUSP 123, Functions and Modeling Barry Minai Date: 04/23/2012 Office of the Registrar For problems and questions about this web page contact icd@u.washington.edu, otherwise contact the instructor or department directly. Modified:March 9, 2014
Modify Your Results Passing the Georgia Geometry End of Course Test will help you review and learn important concepts and skills related to high school mathematics. To help identify which areas are of great-est challenge for you, first take the diagnostic test, then complete the evaluation chart with your instructor in order to help you identify the chapters which require your careful attention. Number theory, rational numbers and percents, real numbers and inequalities, linear equations, congruence, similarity, and transformations are some of the topics covered. Real life applications and uses of the math that students are being asked to learn continues to be incorporated in the text and exercises. (Back Cover) AMERICA'S TOP TEEN DETECTIVES TEAM UP TO UNCOVER AN OPEN MARKET IN CRIME NANCY DREW has traveled to the charming Mexican town of San Miguel de Allende to help Helen and David Oberman avert a disastrous criminal scandal at their prestigious art school. The Obermans have learned that the campus has become a focal point of counterfeiters. Someone is producing bogus green cards, which will be used to exploit and smuggle illegal aliens into the United States. Meanwhile... THE HARDY BOYS have also made their way south to visit the Perelis family in Mexico City. It began as a pleasure trip, but when a priceless Mayan jade mask is stolen from the Perelis art gallery, Frank and Joe get down to business. Discovering an intriguing connection between the theft and the forgers in San Miguel, Nancy and the boys must act quickly to trace the connection to its source -- and find the shocking truth behind the ancient mask of mystery ... This book is preparing students for success in mathematics in the middle grades and beyond. In this course students will study important middle grade mathematics concepts and see how they are related and also find a gradual approach to understanding the underlying principles of algebra and geometry. Nancy is tending her prize delphiniums when a mysterious carrier pigeon lands in her yard. The message it carries, "Bluebells are now singing horses," is so odd that it piques her curiosity, causing her to contact the registry for the birds. Meanwhile, housekeeper Hannah Gruen takes a fall and must be treated at the local orthopedist's office. The attending physician, Dr. Spires, later confides to Carson Drew and Nancy that he was forced to tend an elderly woman for her shoulder -- the drivers of a car blindfolded him when they drove him there, so he wouldn't be able to guess her location, leading him to believe the patient was a prisoner. The only clue to her identity is a bracelet with a family crest, and the doctor's belief that she was being held on Larkspur Lane. Nancy, of course, immediately sets out to track the crest, discovering that it belongs to the Eldridge family of St. Louis. In 1825, sixteen-year-old Sophie, the Duchess of Edmonton, falls in love with Henry Patman. But Sophie's sister, Melanie, has also fallen for Henry's rugged charm, and Melanie will do anything to keep Sophie and Henry apart. John Patman loses his heart to London actress Katherine Richmond. He's too poor to ask for her hand in marriage, so he swears he'll strike it rich in the oil fields of Texas. But how long will Katherine wait? Dr. Cassandra Vanderhorn meets wounded soldier Spencer Lighting a World War II veterans' hospital. After he recovers, they marry, and he returns to the front. Then Cassandra receives a telegram bearing terrible news... Marie Vanderhorn has found her soul mate in Hank Patman. When Marie is stricken with Leukemia, she breaks off the relationship and keeps her suffering a secret. Hank vows that he'll love Marie forever. But then Alice Robertson crosses his path... Click here to find out more about the 2009 MLA Updates and the 2010 APA Updates. Laurie Kirszner and Stephen Mandell, best-selling authors and experienced teachers, know what works in the classroom. They have a knack for picking just the right readings. In Patterns for College Writing, they provide students with exemplary rhetorical models and instructors with class-tested selections. The readings are a balance of classic and contemporary essays by writers such as Sandra Cisneros, Deborah Tannen, E. B. White, and Henry Louis Gates Jr. And with more examples of student writing than any other reader,Patterns has always been an exceptional resource for students. Patterns also has the most comprehensive coverage of the writing process in a rhetorical reader with a five-chapter mini-rhetoric; the clearest explanations of the patterns of development; and the most thorough support for students of any rhetorical reader. With loads of exciting new readings and updated coverage of working with sources,Patterns for College Writing helps students as no other book does. There's a reason it is the best-selling reader in the country. Laurie Kirszner and Stephen Mandell, authors with nearly thirty years of experience teaching college writing, know what works in the classroom and have a knack for picking just the right readings. InPatterns for College Writing, they provide students with exemplary rhetorical models and instructors with class-tested selections that balance classic and contemporary essays. Along with more examples of student writing than any other reader,Patternshas the most comprehensive coverage of active reading, research, and the writing process, with a five-chapter mini-rhetoric; the clearest explanations of the patterns of development; and the most thorough apparatus of any rhetorical reader, all reasons whyPatterns for College Writingis the best-selling reader in the country. And the new edition includes exciting new readings and expanded coverage of critical reading, working with sources, and research. It is now available as an interactive Bedford e-book and in a variety of other e-book formats that can be downloaded to a computer, tablet, or e-reader. Avery Washington has spent his entire life in Patterson Heights, a Baltimore neighborhood with a mean rep. It's a good place to grow up--it has heart and soul as well as a few street hustlers, and plenty of solid families just like his. Then one day, his older brother Rashid ends up in the wrong place at the wrong time, and Avery's life changes forever. Once an A-plus student with hopes of going to college, Avery now has to rethink his future. While his parents struggle to cope with the loss of one son, Avery has to prove himself at his new school, and deal with pressures he can't admit to anyone--not even Natasha, the one person who seems to really get him. But now he'll have to choose between doing what's expected and being true to himself. . . between maintaining a reputation and growing up too soon. . . . The Tears of All Oceans are missing. Six magnificent rose-colored pearls, which inspire passion and greed in all who see them, have been stolen and passed from hand to hand, leaving a cryptic trail of death and deception in their wake. And now Ublaz Mad Eyes, the evil emperor of a tropical isle, is determined to let no one stand in the way of his desperate attempt to claim the pearls as his own. At Redwall Abbey, a young hedgehog maid, Tansy, is equally determined to find the pearls first, with the help of her friends. And she must succeed, for the life of one she holds dear is in great danger. Getting out of prison was like being born again, said Patrick Pennington. His adoring girl friend, seventeen-year-old Ruth Hollis, was waiting for him. Professor Hampton, Pat's piano teacher, had waited, too, for his impetuous star pupil to get out and get back to his music again. Now it looked like a sure, straight road to success, if Pat could just keep himself out of trouble and stick with his studies. But trouble and Pat Pennington have an affinity for each other. When Ruth tells him she is going to have his baby, Pat must face a new kind of problem-one that threatens both his personal happiness and his future as a concert pianist. Patrick Pennington, the rebellious and talented anti-hero of Pennington's Last Term and The Beethoven Medal, doesn't settle easily into the role of husband, father, and breadwinner. With humor, compassion, and deep insight, K. M. Peyton portrays a very young, very loving couple's rocky first year of marriage.Written for individuals who have little or no knowledge of the arts, Perceiving the Arts has a specific and limited purpose: to provide an introductory, technical, and respondent-related reference to the arts and literature. Intended to give basic information about each of the arts disciplines-drawing, painting, printmaking, photography, sculpture, architecture, music, theatre, dance, cinema, landscape architecture, and literature-the book seeks to give its readers touchstones concerning what to look and listen for in works of art and literature
This site allows one access per day per computer free of charge. This applet allows students to graph up to six different linear inequalities in six different colors with solid or broken lines. The s... More: lessons, discussions, ratings, reviews,... This site allows one access per day per computer free of charge. This applet allows students to establish an objective function, and then graph up to five constraints in different colors. Students c... More: lessons, discussions, ratings, reviews,... This packet contains a copy of the original problem used to create the activity, rationale and explanation behind the "Change the Representation" focal activity, and some thoughts on why this activity... More: lessons, discussions, ratings, reviews,... This flash program is a way to give your students endless practice on solving simple linear inequalities. It randomly generates ten problems which you can print and distribute. An answer sheet is al... More: lessons, discussions, ratings, reviews,... A free web-based function graphing tool. Graph up to three different functions on the same axes. Functions can refer to up to three independent variables controlled by sliders. As you move
The purposes, principal audience, the main topics, and chapter design are described here. MATLAB® advances in comparison to such popular software as Mathematica, Mathcad, Maple, and R, are briefly lightened. The differences between the present and author's previous book are discussed briefly. The MATLAB® windows, starting procedures; basic language constructions and commands; vectors, matrix and array manipulations, flow control operations are presented in this chapter. Basic commands are demonstrated on various bio-applications such as RNA volume computing, Arrhenius' equation, RNA bases, and many others. The questions and life-science problems together with answers to some of them are given in conclusion. Available two and three dimensional graphic commands are described in the chapter. The line, bar, histogram, and many other plots are generated with the MATLAB® plotting tool. The appropriate commands with their graphical possibilities are presented by examples of bio-data, equilibrium reaction, microorganism population growth, Ponderal index, etc. The questions and life-science problems together with answers to some of them are given in conclusion. Editor Window, script- and function files are accurately described. The commands for solving algebraic equation, for integration, differentiation, interpolation and extrapolation are introduced with applications to numerical problems of bioengineering, particularly such as heat sterilization time, population dynamics, bacterial population amount, etc. The questions and life-science problems together with answers to some of them are given in conclusion. Specific ordinary differential equations and the ODE solver are briefly presented together with examples for bio-systems that can be represented by differential equations, one or a set. The solutions are demonstrated for the bio-molecular reaction, the predator-prey model, the drug dissolution, the batch reactor, etc. The questions and life-science problems together with answers to some of them are given in conclusion. The polynomial fitting commands and time series calculations are presented. The Basic Fitting and Time Series Tool interfaces are introduced through applications to the drug dose-blood pressure relation, the hazardous substances level in the air, the plankton concentration, time series forecasting, temperature monthly average predictions, and others. The questions and life-science problems together with answers to some of them are given in conclusion.
Helping students through their GCSE maths course, this title provides short units to facilitate quick learning. Thoroughly covering the range of Intermediate topics, the explanations are designed to work from the basics up to examination standard. Synopsis: Edexcel GCSE Mathematics 16+ helps students through their maths course in a year, whether they are new to GCSE or preparing to retake the exam. It provides coverage of all the key intermediate tier topics. Edexcel GCSE Mathematics 16+ helps students through their maths course in a year, whether they are new to GCSE or preparing to retake the exam. It provides coverage of all the key intermediate tier topics.
More About This Textbook Overview Every mathematician is involved in publishing. Throughout our careers, we are expected to publish our work: in journals, conference proceedings and books. Later, we may be called to serve as an editor for a journal or book series. However, our training is for doing the mathematics, not publishing it. Here, finally, is a guidebook to the publishing of mathematics. It describes both the general setting of mathematical publishing and the specifics of all the various publishing situations a mathematician may encounter. As with Steven Krantz's other books, the style is engaging and frank. He provides insight on getting your book published, getting organized as an editor, and what to do when things go wrong. He describes the people of publishing, the language of publishing (including a glossary), and the process of publishing both books and journals. Steven G. Krantz is an accomplished mathematician and an award-winning author. He has published more than 130 research articles and 45 books. He has worked as an editor of several book series, research journals and the AMS Notices, and founded the journal, The Journal of Geometric Analysis. Other titles by Steven Krantz available from the AMS are How to Teach Mathematics, A Primer of Mathematical Writing, A Mathematician's Survival Guide, and Techniques of Problem Solving
Real Analysis 9781852333140 ISBN: 1852333146 Publisher: Springer Verlag Summary: Understanding the concepts and methods of real analysis is an essential skill for every undergraduate mathematics student. Written in an easy-to-read style, Real Analysis is a comprehensive introduction to this core subject and is ideal for self-study or as a course textbook for first and second-year undergraduates. Combining an informal style with precision mathematics, Real Analysis covers all the key topics with f...ully worked examples and exercises with solutions. Featuring: * Sequences and series - considering the central notion of a limit * Continuous functions * Differentiation * Integration * Logarithmic and exponential functions * Uniform convergence * Circular functions All these concepts and techniques are deployed in examples in the final chapter to provide the student with a thorough understanding of this challenging subject. Howie, John M. is the author of Real Analysis, published under ISBN 9781852333140 and 1852333146. Six hundred eighty three Real Analysis textbooks are available for sale on ValoreBooks.com, one hundred four used from the cheapest price of $26.31, or buy new starting at $37.48.[read more