text
stringlengths
6
976k
token_count
float64
677
677
cluster_id
int64
1
1
Ships From:Secaucus, NJShipping:StandardComments: This book finds the right balance between mathematics and economic examples, providing a text th... [more] This book finds the right balance between mathematics and economic examples, providing a text that is demanding in level and broad ranging in content, whilst remaining accessible and interesting to its target audience. [less]
677.169
1
Vendors/Publishers Horizons Math 3 Student Book 1 $18.85 Sale: $16.97 Save: 10% off Horizons Math 3 builds on familiar concepts. Multiplication and division are thoroughly covered, and new concepts such as simple geometry, map reading, temperature in Fahrenheit and Celsius, and the Metric system present new challenges to your students. Grade
677.169
1
Precalculus Online and Books Precalculus for Distance Learning Precalculus is a continuation of topics covered in Algebra 2, including trigonometry, polynomials, functions and their inverses, equations, and complex numbers. New topics include conic sections and polar graphs, matrices, and statistics. The course concludes with an introduction to calculus through sequences, limits, and derivatives. Dr. Garry Conn teaches this course. This course includes an abridged electronic version of the teacher's edition and student textbook that can be viewed while logged on to bjupressonline.com. >>Click the Resources tab to view technical requirements for Distance Learning Online and information about the course's instructorAbout the Instructor Dr. Garry Conn, BA, MAT, EdD Dr. Garry Conn grew up in a Christian home and made his own profession of faith at a Christian camp in southern Ohio at the age of nine. Dr. Conn's own interest in math was influenced by his high school geometry teacher who enjoyed teaching and made the class enjoyable for the students as well, even those that did not like math. Dr. Conn graduated with a BA in Bible Education with a minor in math from Bob Jones University, an MAT in math from The Citadel, and an Ed.D. in curriculum and instruction from Bob Jones University.
677.169
1
Welcome to CoreStandards.org, the official online home of the Common Core State Standards. The website has been refreshed to make it easier to learn more about these consistent academic guidelines created to help all students succeed. Describe qualitatively the functional relationship between two quantities by analyzing a graph (e.g., where the function is increasing or decreasing, linear or nonlinear). Sketch a graph that exhibits the qualitative features of a function that has been described verbally.
677.169
1
A Few Thoughts on Why We Learn Algebra about math, the last thing you want to hear is that you'll "need" to be able to do math in order to live. That might cause you to take those responses as a sign that you should not venture anywhere near computer science or physics, or ever rent an apartment or own a car. What this student needed to hear was the larger picture of why math is useful even if you never touch another x or y in your life. So here are my thoughts, in the form of an example from my own life. When you get right down to it, at its most basic level, algebra centers around the idea that you can add, subtract, multiply, or divide both sides of an equation by the same number and the equation will continue to be true. That very basic concept of "doing the same thing to both sides" has the implication of allowing you to rewrite the same equation a multitude of different ways without changing its value. In essence, algebra is problem solving at its most basic. You start with what you know, and by working step by step through rewriting the equation while maintaining its value, you arrive at a version of the equation that makes the unknown element clear. The whole time, the laws of algebra remind you that you're not changing what the equation means; you're just rewriting it in a way that's easier to work with and understand. This type of step-by-step problem solving has a multitude of uses in everyday life that don't involve a single number. Here's my example. One evening in college, I arrived back at my dorm building after a long day of classes, only to find that my wallet was not in my bag. I had no idea how long I'd been without my wallet, and even less idea where it was. On top of that, I had a small window of time in which I was supposed to go home and change out my books before heading out again, so I needed to get into the dorm NOW, which I couldn't do without my student ID card, which was – you guessed it – in my wallet. So what do I do? Well, I'll be honest, I began to panic slightly. But I worked through the panic and figured out my first plan: retrace my steps until I found my wallet. Fortunately, all of my classes that day had been in the same building, so I didn't have far to go. Unfortunately, my wallet was not anywhere on the path I'd taken from the dorm to the classroom, the path home, or anywhere in between. The wallet was lost. Having hit a dead-end on that front, I decided to set that problem aside and deal with the second issue: I still needed to get into the dorm to change out my textbooks. I figured I'd work on getting into the dorm, and perhaps once I was there more options for the lost wallet would present themselves. So instead of heading for the back door, which required an ID swipe to get in, I walked around to the front entrance and went into the lobby (a public area). I then headed over to the door that led to my wing, and killed time by pretending to read the bulletin board on the wall nearby. Soon, another student came by and swiped her card to open the door. I hurriedly slipped in behind her before the door closed, knowing that most people ignored the signs saying to not let anyone else in after you. I ran up to my room, opened the door (thankfully I still had my keys!) and there was my wallet, lying on the floor in the middle of the room. So what does any of this have to do with algebra? Well, compare my problem-solving strategies to the process of solving a system of equations. In my case, I had two variables: I needed to get into the dorm, and my wallet was gone. I started by trying to find my wallet – when solving a system, you start by solving one equation for one variable. I got as far as I could go on that path and eventually ended up with wallet = gone. I had to set that equation aside for a moment and deal with the other variable, just as you then switch equations in the system. I plugged "I don't have my ID" into the equation of "getting into the dorm" and solved that problem using what I knew about the building and the residents' laziness, and managed to get into my room (I solved for "I need to get into the dorm"). Once in my room, the first equation became solvable again, since my wallet turned out to be there – right where it had fallen out of my bag before I left the room that morning. This may sound way too coincidental, but the truth is that algebraic reasoning is incredibly important for a lot of tasks that have nothing to do with numbers. The ability to rewrite an equation while maintaining its value until the answer presents itself is at the heart of all problem-solving abilities. I often remind my students of the larger usefulness of the skills learned in math class by encouraging them to "take the numbers out of it." What exactly are you doing in a broader sense, and how might you be able to use those skills in other situations? Give it a try – you might find that you like math more than you thought.
677.169
1
This series of videos contains 180 Worked Algebra I examples (problems written by the Monterey Institute of Technology and Education). You should look at the "Algebra" playlist if you've never seen algebra before or if... This series of videos, created by Salman Khan of the Khan Academy, features topics covered from very basic algebra all the way through algebra II. This is the best algebra playlist to start at if you've never seen lesson involves economics and mathematical materials. Students will use their knowledge of exponents to compute an investment's worth using a formula and a compound interest simulator. They may also use the model... This lesson helps students understand the concept of inflation in a mathematical context. Students will learn about the Consumer Price Index and will use it to compare the changing worth of a dollar over several years....
677.169
1
Elementary Stat Using Ti83/ 84 Plus Calculator -With CD - 2nd edition Summary: Key Message: Elementary Statistics Using the TI-83/84 Plus Calculator,Second Edition, guides students through the concepts behind the calculations, raising confidence in their ability to do statistics. Known for being easy both to teach and to learn from,Elementary Statistics Using the TI-83/84 Plus Calculator, Second Edition,features an engaging writing style, an abundance of relevant exercises with real data, and an emphasis on interpretation of statistical results. In addition, th...show moreis text provides extensive information on using the TI-83 and TI-84 Plus (and Silver Edition) calculators for statistics, with information on calculator functions, images of screen displays, and projects designed exclusively for the calculator. Key Topics:Introduction to Statistics; Summarizing and Graphing Data; Statistics for Describing, Exploring, and Comparing Data; Probability; Probability Distributions; Normal Probability Distributions; Estimates and Sample Sizes; Hypothesis Testing; Inferences from Two Samples; Correlation and Regression; Multinomial Experiments and Contingency Tables; Analysis of Variance; Nonparametric Statistics; Statistical Process Control; Projects, Procedures, Perspectives Market:For all readers interested in Statistics ...show less This book has a light amount of wear to the pages, cover and binding.Blue Cloud Books ??? Hot deals from the land of the sun. $2.9397 +$3.99 s/h Good OwlsBooks-TRM35 +$3.99 s/h Good Quality School Texts OH Coshocton, OH 2007-05-04 Hardcover Good Names on inside cover and numbers on bookedge; no other internal marking/highlighting
677.169
1
Paperback. Book Condition: New. 2nd. 137mm x 20mm x 208mm. Paperback. Packed with in-depth, student-friendly topic reviews that fully explain everything about the subject, this title includes coverage of fundamental maths concepts, sets, decimals, fractions.Shipping may be from multiple locations in the US or from the UK, depending on stock availability. 284 pages. 0.340. Bookseller Inventory # 9780738611198 Book Description: Research Education Association,U.S., United States, 2014. Paperback. Book Condition: New. 2nd edition. 206 x 136 mm. Brand New Book. This title presents all the fundamentals at your fingertips! Each Super Review is packed with in-depth, student-friendly topic reviews that fully explain everything about the subject. The Basic Math Pre-Algebra Super Review includes coverage of fundamental maths concepts, sets, decimals, fractions, and more! Take the Super Review quizzes to see how much you ve learned - and where you need more study. It makes an excellent study aid and textbook companion and is ideal for self-tuition. Bookseller Inventory # AAC9780738611198 Pearson Prentice-Hall, 2008. Book Condition: Used: Like New. Unused! Book Leaves in 1 Business Day or Less! Leaves Same Day if Received by 2 pm EST! Slight shelf wear. Contents Unused. Like New. Bookseller Inventory # 1005140023 Book Description: Createspace, United States, 2011. Paperback. Book Condition: New. 203 x 133 mm. Brand New Book ***** Print on Demand *****.This is no ordinary math book! How to Homeschool Math - Even if you Hate Fractions!! is a humorous and lively parent-to-parent chat about the ups and downs of homeschooling math. This groundbreaking and insightful book outlines a foolproof method, not only to teach your kids math - but to get them to love it too! She calls it Full-Contact Math, and anyone can do it! This book answers many of the questions homeschool parents have about math: Which curriculum should I use? How much math should my child do each day? How much help should I give my child on math? What level should my child be at for his age? What should he take first: Algebra or Geometry? When should I get a tutor? What the heck is Pre-Algebra ? How on earth can we homeschool Calculus?! .and most of all: Why does my kid HATE math? .and how can I change that? In this sometimes serious, sometimes laugh-out-loud funny book you will learn why whatever curriculum you do choose is just one of many things to consider when homeschooling math. It is what you do with the curriculum that counts! A homeschool mom and math tutor herself, Robin draws on her years of experience teaching not only her own kids, but also other homeschoolers as well as school children. Bookseller Inventory # APC9781463673543 Book Description: Createspace, United States, 2011. Paperback. Book Condition: New. 229 x 152 mm. Brand New Book ***** Print on Demand *****.A pre-algebra adventure story that follows Oona and friends through the United Sets of Numerica as the citizens of Fraction Valley prepare to go to war against Decimal City. This mathematical fiction story was written by a Mathematics Learning Specialist for middle and high school math students. Bookseller Inventory # APC9781463756642 Book Description: Goods of the Mind, LLC, United States, 2013. Paperback. Book Condition: New. 279 x 216 mm. Brand New Book ***** Print on Demand *****. About Competitive Mathematics for Gifted Students This series provides practice materials and short theory reminders for students who aim to excel at problem solving. Material is introduced in a structured manner: each new concept is followed by a problem set that explores the content in detail. Each book ends with a problem set that reviews both concepts presented in the current volume and related topics from previous volumes. The series forms a learning continuum that explores strategies specific to competitive mathematics in depth and breadth. Full solutions explain both reasoning and execution. Often, several solutions are contrasted. The problem selection emphasizes comprehension, critical thinking, observation, and avoiding repetitive and mechanical procedures. Ready to participate in a math competition such as AMC-8, AMC-10, Math Kangaroo in USA, Math Leagues, USAMTS, or AIME? This series will open the doors to consistent performance. About Level 3 This level of the series is designed for students who can solve linear equations, are fluent with fractions, and can factor into primes. The problem sets are designed to strengthen specific areas where we know students have difficulty on AMC-8 and AMC-10. The level 2 books are a strong preparation for AMC-8 and a partial preparation for AMC-10 and AIME. Level 2 consists of: Word Problems (volume 9), Arithmetic and Number Theory (volume 10), Operations and Algebra (volume 11), Geometry (volume 12), and Combinatorics (volume 13). On the contest list for this level: MATHCOUNTS, Math Kangaroo levels 5-6 and 7-8, MOEMS-M, Purple Comet, AMC-8, AMC-10. The computational complexity makes these problem sets useful for preparing the AIME in the long run. About Volume 10 - Arithmetic and Number Theory The problem sets reflect the use of the most elementary facts of number theory in challenging ways. Instead of imitating contest problems, we have focused on presenting questions that explore the nuts and bolts used to create problems. This volume is particularly suitable for young students who aim to do well on AIME in later years and have the patience to explore the elementary facts of number theory in depth. We continue in level 4 with more advanced number theory. Fluency with order of operations and the ability to handle simple algebraic expressions are pre-requisites. Bookseller Inventory # APC9780615943855 American Education Publishing, 2004. Paperback. Book Condition: New. Might have light shelf wear.Designed specifically for children in grade 4, this 352 page workbook is a step-by-step guide that helps children develop essential math skills and concepts. Perfect for drill and review this book introduces math applications such as multiplication and division, word problems, fractions, measurements, graphs and pre-algebra.Featuring a complete answer key this workbook includes straightforward, easy-to-understand directions. Stickers, math puzzles, and a poster are also included as an added bonus. Bookseller Inventory # 130916168 Research Education Association,U.S., United States, 2012. Paperback. Book Condition: New. 206 x 136 mm. Brand New Book. The fundamentals of maths at your fingertips! Each Super Review is packed with in-depth, student-friendly topic reviews that fully explain everything about the subject. "The Basic Math Pre-Algebra Super Review"!. Bookseller Inventory # AAJ9780878914616 Learning Express Llc, United States, 2009. Paperback. Book Condition: New. 255 x 183 mm. Brand New Book. You don t have to be a genius to become an algebra ace-you can do it in just 15 minutes a day Packed with short and snappy lessons, Junior Skill Builders: Algebra in 15 Minutes a Day makes learning algebra easy. It s true: making sense of algebra doesn t have to take a long time .and it doesn t have to be difficult! In just one month, students can gain expertise and ease in all the algebra concepts that often stump students. How? Each lesson gives one small part of the bigger algebra problem, so that every day students build upon what was learned the day before. Fun factoids, catchy memory hooks, and valuable shortcuts make sure that each algebra concept becomes ingrained. With Junior Skill Builders: Algebra in 15 Minutes a Day , before you know it, a struggling student becomes an algebra pro-one step at a time. In just 15 minutes a day, students master both pre-algebra and algebra, including: fractions, multiplication, division, and other basic math; translating words into variable expressions; linear equations; real numbers; numerical coefficients; inequalities and absolute values; systems of linear equations; powers, exponents, and polynomials; quadratic equations and factoring; rational numbers and proportions; and, much more! In addition to all the essential practice that kids need to ace classroom tests, pop quizzes, class participation, and standardized exams, Junior Skill Builders: Algebra in 15 Minutes a Day provides parents with an easy and accessible way to help their children excel. Bookseller Inventory # AAC9781576856734 Book Description: Createspace, United States, 2011. Paperback. Book Condition: New. 229 x 152 mm. Brand New Book ***** Print on Demand *****. This short book is intended to help those struggling with basic pre-algebra and beginning algebra skills. Written by a former high school math teacher, it simplifies topics such as fractions and exponents by using a mechanic s toolbox approach to problem solving. Bookseller Inventory # APC9781463777906 Book Description: Career Press, United States, 2011. Paperback. Book Condition: New. Enhanced, Updated ed. 229 x 153 mm. Brand New Book. Homework Helpers: Basic Math and Pre-Algebra will help build a solid mathematical foundation and enable students to gain the confidence they need to continue their education in mathematics. Particular attention is placed on topics that students traditionally struggle with the most. The topics are explained in everyday language before the examples are worked. The problems are solved clearly and systematically, with step-by-step instructions provided. Problem-solving skills and good habits, such as checking your answers after every problem, are emphasized along with practice problems throughout, and the answers to all of the practice problems are provided. Homework Helpers: Basic Math and Pre-Algebra is a straightforward and easy-to-read review of arithmetic skills. It includes topics that are intended to help prepare students to successfully learn algebra, including: A[a A[ Working with fractions A[a A[ Understanding the decimal system A[a A[ Calculating percentages A[a A[ Solving linear equalities A[a A[ Graphing functions A[a A[ Understanding word problems. Bookseller Inventory # ABZ9781601631688 Book Description: John Wiley & Sons Inc, 2010. Paperback. Book Condition: New. 14.6 x 22.22 cm. Focuses on critical concepts taught in a typical pre-algebra course, from fractions, decimals, and percents to standard formulas and simple variable equations.Our orders are sent from our warehouse locally or directly from our international distributors to allow us to offer you the best possible price and delivery time. book. Bookseller Inventory # MM-20410173
677.169
1
Elementary Algebra -Text Only - 6th edition ISBN13:978-0077224790 ISBN10: 0077224795 This edition has also been released as: ISBN13: 978-0073533506 ISBN10: 0073533505 Summary: Elementary Algebra, 6/e is part of the latest offerings in the successful Dugopolski series in mathematics. Given the importance of examples within a math book, the author has paid close attention to the most important details for solving the given topic. Dugopolski includes a double cross-referencing system between the examples and exercise sets, so no matter which one the students start with, they will see the connection to the other.132.35
677.169
1
Description:Students will make the necessary conversions using basic equivalency tables for standard measurements used in cooking. The problems in this activity are from the San Diego Mesa College Culinary Arts department and are examples of real world situations. In most Pre-algebra classes unit conversion comes toward the end of the course and is taught in the context of ratios and proportions. This lab does not rely on any knowledge of proportions; it is done completely using the dimensional analysis method illustrated in the example. Prerequisites: Arithmetic operations with fractions Dimensional analysis Familiarity with standard and metric units of measure (the actual conversions needed are given in the lab). Description: Students will make the necessary conversions using basic equivalency tables for standard measurements used in cooking. The problems in this activity are from the San Diego Mesa College Culinary Arts department and are examples of real world situations.
677.169
1
Calculus is one of the greatest inventions of the human intellect. It has proved itself over centuries by acting as the "language of continuous change" in subjects ranging from physics to finance. Calculus will continue to be important, but Mathematica has changed what educated people need to know in order to make calculus a useful part of their lives. I will discuss three ways Mathematica is impacting calculus instruction: Calculus WIZ, NetMath Calculus, and Calculus: The Language of Change. These three highly developed experiments show how students can begin learning calculus with Mathematica, resulting in faster mastery of skills, deeper involvement in the mathematical development, and solution of more compelling and interesting problems. Mathematica contains a vast body of "classical mathematical" knowledge. The challenge to instructors is to make our students "educated users" of this knowledge without having them earn Ph.D.'s in math. The potential is that "ordinary" people will be able to apply this new organization of knowledge going far beyond traditional calculus. Keith Stroyan is Professor of Mathematics at the University of Iowa. Professor Stroyan wrote the research monographs Introduction to the Theory of Infinitesimals and Foundations of Infinitesimal Stochastic Analysis as well as numerous research articles on Robinson's modern theory of infinitesimals. He has also taught a full spectrum of mathematics courses including remedial algebra, high school analytical geometry, most of the undergraduate math curriculum, graduate courses, and research-level topics courses such as mathematical ecology and stochastic differential equations.
677.169
1
Calculus reform: catching the wave? Calculuscalculus, branch of mathematics that studies continuously changing quantities. The calculus is characterized by the use of infinite processes, involving passage to a limit—the notion of tending toward, or approaching, an ultimate value. Reform: Catching the Wave? Calculus is big, important--and in trouble. This was one of the messages that came out of a recent conference at the National Academy of Sciences in Washington, D.C., on the future of calculus education. The meeting attracted more than 600 mathematiciansMathematicians by letter: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z See also Requested mathematicians articles (by country, etc.) List of physicists External links , educators and other professionals worried about the state of calculus teaching. The large attendance reflected a growing feeling that something ought to be done to reform the way calculus is taught (SN:4/5/86, p.220). "We are not doing a good job in teaching what we are teaching,' says mathematician Ronald G. Douglas, physical sciences and mathematics dean at theWe now have an opportunity to do something about the trouble and to make [calculus] even more important.' By almost any measure, the teaching of calculus is a huge enterprise. In any given semesterse·mes·ter n. One of two divisions of 15 to 18 weeks each of an academic year. [German, from Latin (cursus) s, about 12,000 calculus instructors face more than 750,000 students in 7,500 high schools, colleges and universities. The number of students is double the figure of 20 years ago. These calculus courses represent almost $250 million in tuition and other fees, along with the millions invested by publishers in textbooks and other aids. Furthermore, success in calculus is the gateway to professional careers, especially in the sciences and engineering. Some business schools and other college departments also require students to take a calculus course. For many students, calculus is the only college-level mathematics course they encounter. "A lot of people have a stake in calculus,' says Douglas. "That makes it that much harder to change it.' But the need for changes is evident in the list of problems faced by current calculus programs: unwieldy textbooks, poor teaching, excessively large classes, low standards, simple-minded exams. Perhaps as many as a third of all students enrolled in calculus courses fail or withdraw, according toaccording to prep. 1. As stated or indicated by; on the authority of: according to historians. 2. In keeping with: according to instructions. 3. a recent survey by the Mathematical Association of America The Mathematical Association of America (MAA) is a professional society that focuses on undergraduate mathematics education. Members include teachers at the college and high school level; graduate and undergraduate students; and mathematicians and scientists. . Although many mathematicians and educators agree that these problems exist, not everyone describes the situation as a crisis that clearly threatens the future viability of calculus courses. "There's no crisis in calculus,' says Leonard Gillman of the University of Texas in Austin. "We have a solid program, and people are learning some mathematics.' Two simple ways to improve the current state of calculus, he says, are by letting students use computers to practice routine problem-solving skills and by enforcing prerequisites so that students some into calculus classes properly prepared. However, the poor quality of much calculus teaching, especially in university classes, is more difficult to deal with. "I have a lot of colleagues who are wedded to their research,' says Gillman, "and they really much about calculus [teaching].' He adds, "There's nothing wrong with sprucing up the curriculum. We've been doing that for many years, but the teaching is getting worse.' Other mathematicians see a more direct threat to the present situation in which college and university mathematics departments teach calculus courses not only for students intending to major in mathematics but also for those planning to enter all other fields. "Calculus is our most important course,' says Gail S. Young of the National Science Foundation (NSFNSF - National Science Foundation ), "and the future of our subject . . . depends on improving it.' For many students, calculus represents a significant barrier on the road to a professional career, says Robert M. White, president of the National Academy of Engineering. "It must become a pump instead of a filter in the pipeline,' he says. "Calculus is really exciting stuff, and we're not presenting it as exciting stuff.' Says Douglas, "We've got to get back to the idea that teaching calculus is important. We have to devote time to it.' Private university in Hamilton, N.Y. It was founded in 1819 as a Baptist-affiliated institution but became independent in 1928. It offers primarily a liberal arts curriculum for undergraduates, with some master's degree programs in arts and teaching. in Hamilton, N.Y., then calculus could end up being taught largely in high schools. Another possibility is that client disciplines such as physics or engineering may begin to teach calculus classes better tailored to their needs. Two recent developments may push forward attempts to reform calculus instruction. One is the increasing use of computers and the development of new calculators capable of manipulating symbols. Some calculator models now available allow students, just by pushing a few buttons, to do about 90 percent of the calculations required by typical calculus tests and exams or most textbook exercises. At the same time, concerns about the state of all undergraduate education , the need for changes in mathematics and science programs from kindergarten to grade 12 (SN:1/31/87, p.72) and worries about cultural literacyCultural literacy is the ability to converse fluently in the idioms, allusions and informal content which creates and constitutes a dominant culture. From being familiar with street signs to knowing historical reference to understanding the most recent slang, literacy demands , technological literacyTechnological literacy is the ability to understand and evaluate technology. It complements technological competency, which is the ability to create, repair, or operate specific technologies, commonly computers. (SN:2/22/86, p.118) and other knowledge gaps are generating a wave of interest in educational reform. Recently, NSF decided to focus on calculus education as one of two key areas for support and proposed a $2 million program for the development of calculus curriculum materials. "It's a start,' says Douglas, "and it indicates a national interest in calculus reform. It's a matter of catching the wave.' Nevertheless, the sheer size and inert of the calculus establishment make it hard for reformers to introduce changes. The changes, says Douglas, must come by way of a large number of local efforts that gradually spread throughout the educational system. "We're planting seeds,' he says. "We're not ready to harvest yet.' "Changing calculus may be a greater battle than we ever imagined, but it's a battle worth fighting,' says Tucker. "I'm sure we can do better, but we can't do it alone.' Photo: John W. Kenelly of Clemson (S.C.) University demonstrates that a sophisticated calculator can now do many kinds of calculus problems. COPYRIGHT 1987 Science Service, Inc. No portion of this article can be reproduced without the express written permission from the copyright holder.
677.169
1
Find an Easton, MA Algebra 2Algebra is really about formalizing mathematics into a coherent way of reading & writing it so it can be used to solve problems. Typically, algebra includes learning about the different kinds of numbers, learning how to write expressions and equations, and then learning to solve those equations. It's also when the infamous "word problem" gets introduced.
677.169
1
took it in high school. I think the material in Algebra 2 is usually taught in lower-level and/or remedial courses in college. It generally covers more complex equations, systems, sets, etc. in preparation for Precalculus. This is from my own experience though, so it may differ for others
677.169
1
This set accompanies Saxon Math's Advanced Math curriculum, and is perfect for additional students or co-op settings. This set includes 31 Advanced Math test forms with full test solutions. The answer key features line-listed answers to all student textbook problem sets. A recommended test administration schedule is included Great product We already had the student book for this course, but these products complete the package and gave us all we needed as homeschoolers to start my son on his Pre-calculus road. Share this review: 0points 0of0voted this as helpful. Review 2 for Saxon Advanced Math, Answer Key Booklet & Test Forms Overall Rating: 5out of5 Date:September 10, 2010 Mary Jane Witter I think it does not get any better than Saxon for homeschool math. Advanced Math is a difficult curriculum but Saxon's step by step lessons are helpful and understandable. I highly recommend Saxon. Share this review: 0points 0of0voted this as helpful. Review 3 for Saxon Advanced Math, Answer Key Booklet & Test Forms Overall Rating: 5out of5 Date:September 30, 2009 Tracey Tillson Our kids have use this book quite successfully so to say that "you get confused because you learn it all at once" might just apply to the previous reviewer, not everyone. And you don't learn it all at once. You learn a bit, practice that, learn more, etc. etc. It's a proven strategy but if it doesn't work for you, use something else. Share this review: 0points 0of0voted this as helpful. Review 4 for Saxon Advanced Math, Answer Key Booklet & Test Forms Overall Rating: 1out of5 Date:September 22, 2009 Natalie Having went through all Saxon classes since Elementary school, I didn't realize that the books combinded every aspect of math. I think that it's a terriable book because of this. It doen't go into depth with geometry or trig very much, and you get all of the concepts confused because you learn them all at once.
677.169
1
Students will develop foundational math skills needed for higher education and practical life skills with ACE's Math curriculum. Algebra 1 PACE 1107 covers simplifying ratios, solving proportions with an unknown, understanding the direct and inverse variation which can exist between two variables in a given equation.Customer Reviews for Algebra 1 PACE 1107 This product has not yet been reviewed. Click here to continue to the product details page.
677.169
1
respected, extremely user-friendly text emphasizes essential math skills and consistently relates math to practical applications so students can see how the math will help them on the job. Visual images are used to engage students and assist with problem solving.
677.169
1
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.
677.169
1
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
677.169
1
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
677.169
1
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]
677.169
1
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.
677.169
1
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.
677.169
1
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:[email protected] 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 [email protected](symfind)On line 104 ==> vars = maple([ vars , minus , ,pi, ]); 226 Chapter 11: TroubleshootingError in ==> C:MATLAB [email protected](makeinline)On line 73 ==> vars = symfind(f);Error in ==> C:MATLAB [email protected] 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
677.169
1
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
677.169
1
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
677.169
1
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.
677.169
1
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.
677.169
1
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.
677.169
1
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.
677.169
1
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
677.169
1
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]
677.169
1
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
677.169
1
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
677.169
1
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
677.169
1
Summary: Focusing on the important ideas of geometry, this book shows how to investigate two- and three-dimensional shapes with very young students. It introduces methods to describe location and position, explores simple transformations, and addresses visualization, spatial reasoning, and the building and drawing of constructions. Activities in each chapter pose questions that stimulate students to think more deeply about mathematical ideas. The CD-ROM features fourteen arti...show morecles from NCTM publications. The supplemental CD-ROM also features interactive electronic activities, master copies of activity pages for students, and additional readings for teachers. ...show less Edition/Copyright: 01 Cover: Paperback Publisher: National Council of Teachers of Mathematics Published: 01/28/2001 International: No 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! $6.49 +$3.99 s/h New AlphaBookWorks Alpharetta, GA 0873535111 MULTIPLE COPIES AVAILABLE - New Condition - Never Used $10.05 +$3.99 s/h VeryGood AlphaBookWorks Alpharetta, GA 087353511178 +$3.99 s/h VeryGood No Particular Books Sun City West, AZ 2001 Very good in very good dust jacket. 98 p. Principles and Standards for School Mathematics Navigations. Audience: General/trade. Excellent condition, not in plastic. Includes CD. Great price. Sh...show moreips fast21 +$3.99 s/h New Textbookcenter.com Columbia, MO Ships same day or next business day! UPS(AK/HI Priority Mail)/ NEW book
677.169
1
Math is tough but Microsoft has just given us a free graphical symbolic calculator to download. It can solve equations, do calculus, work with matrices and plot the results. As they say, why pay more?. Microsoft Mathematics is a interactive tool for doing mathematics and it can do both numeric and symbolic calculations. Give it an equation and it can solve it. Give it a function and it will integrate or differentiate it for you and offer to graph the result. It is an amazing tool and it's easy to use. It is intended for use by students and promoted by Microsoft Education and previously sold for around $20. Now the new Version 4 is available free to download. There hasn't really been much information forthcoming from Microsoft about it and it is almost as if it has been slipped out in the hope that no one will notice. After you have downloaded it you can use it like a simple calculator to do arithmetic, advanced arithmetic even, but you can also use it to do symbolic maths. You can type in an equation and ask it for the solution and in many cases it makes a sensible attempt at an answer. It can do matrix calculations, algebra and calculus. You need the derivative or integral of some function - just type it in and the program will perform the symbolic manipulation for you. It also draws graphs of functions and data and ... well the list goes on. It also comes with a good help file, tutorials and it supports ink input so you can write equations into the edit box. It isn't as good as Mathematica or Maple but it does enough for many users not to need to go beyond it. Given that it is free it also represents a bargain. And yes it has a multibase conversion function so you can use it to do programming calculations. It's a great educational tool but it is also suitable for serious calculations. The only problem is that there is no scripting language for it and no API specification, so it looks as if it can't be easily extended. As it is a .NET WPF application the usual techniques for taking control of it are unlikely to work. This is a shame because with a scripting language it could do so much more. As it stands Microsoft has just given us a free graphical symbolic calculator - why not download it and give it a try. 32- and 64-bit versions are available and it runs under just about everything from Windows XP SP3 up. More Information JPEG is well known, well used and well understood. Surely there cannot be anything left to squeeze out of this old compression algorithm? Mozilla seems to think that we can get more if we are careful. [ ... ] As programmers we often think that users are overly sensitive about their data. What could it hurt to allow the collection of location data, for example. Here is a short video from the ACLU that might [ ... ]
677.169
1
1 Introduction About the Student Version The Student Version of MATLAB® & Simulink® is the premier software package for technical computation, data analysis, and visualization in education and industry. The Student Version of MATLAB & Simulink provides all of the features of professional MATLAB, with no limitations, and the full functionality of professional Simulink, with model sizes up to 300 blocks. The Student Version gives you immediate access to the high-performance numeric computing power you need. MATLAB allows you to focus on your course work and applications rather than on programming details. It enables you to solve many numerical problems in a fraction of the time it would take you to write a program in a lower level language. MATLAB helps you better understand and apply concepts in applications ranging from engineering and mathematics to chemistry, biology, and economics. Simulink, included with the Student Version, provides a block diagram tool for modeling and simulating dynamical systems, including signal processing, controls, communications, and other complex systems. The Symbolic Math Toolbox, also included with the Student Version, is based on the Maple® V symbolic kernel and lets you perform symbolic computations and variable-precision arithmetic. MATLAB products are used in a broad range of industries, including automotive, aerospace, electronics, environmental, telecommunications, computer peripherals, finance, and medical. More than 400,000 technical professionals at the world's most innovative technology companies, government research labs, financial institutions, and at more than 2,000 universities rely on MATLAB and Simulink as the fundamental tools for their engineering and scientific work. Student Use Policy This Student License is for use in conjunction with courses offered at a degree-granting institution. The MathWorks offers this license as a special service to the student community and asks your help in seeing that its terms are not abused. To use this Student License, you must be a student using the software in conjunction with courses offered at degree-granting institutions.1-2 About the Student VersionYou may not use this Student License at a company or government lab, or ifyou are an instructor at a university. Also, you may not use it for research orfor commercial or industrial purposes. In these cases, you can acquire theappropriate professional or academic version of the software by contacting TheMathWorks.Differences Between the Student Version and theProfessional VersionMATLABThis version of MATLAB provides full support for all language features as wellas graphics, external (Application Program Interface) support, and access toevery other feature of the professional version of MATLAB.Note MATLAB does not have a matrix size limitation in this Student Version.MATLAB Differences. There are a few small differences between the StudentVersion and the professional version of MATLAB:1 The MATLAB prompt in the Student Version is EDU>>2 The window title bars include the words <Student Version>3 All printouts contain the footer Student Version of MATLAB This footer is not an option that can be turned off; it will always appear in your printouts. 1-3 1 Introduction Simulink This Student Version contains the complete Simulink product, which is used with MATLAB to model, simulate, and analyze dynamical systems. Simulink Differences. 1 Models are limited to 300 blocks. 2 The window title bars include the words <Student Version> 3 All printouts contain the footer Student Version of MATLAB This footer is not an option that can be turned off; it will always appear in your printouts.1-4 Obtaining Additional MathWorks ProductsObtaining Additional MathWorks Products Many college courses recommend MATLAB as their standard instructional software. In some cases, the courses may require particular toolboxes, blocksets, or other products. Many of these products are available for student use. You may purchase and download these additional products at special student prices from the MathWorks Store at Although many professional toolboxes are available at student prices from the MathWorks Store, not every one is available for student use. Some of the toolboxes you can purchase include: Communications Neural Network Control System Optimization Fuzzy Logic Signal Processing Image Processing Statistics For an up-to-date list of which toolboxes are available, visit the MathWorks Store. Note The toolboxes that are available for the Student Version of MATLAB & Simulink have the same functionality as the full, professional versions. However, these student versions will only work with the Student Version. Likewise, the professional versions of the toolboxes will not work with the Student Version. Patches and Updates From time to time, the MathWorks makes changes to some of its products between scheduled releases. When this happens, these updates are made available from our Web site. As a registered user of the Student Version, you will be notified by e-mail of the availability of product updates. Note To register your product, see "Product Registration" in "Troubleshooting and Other Resources" in this chapter. 1-5 1 Introduction Getting Started with MATLAB What I Want What I Should Do I need to install MATLAB. See Chapter 2, "Installation," in this book. I'm new to MATLAB and Start by reading Chapters 1 through 5 of Learning MATLAB. want to learn it quickly. The most important things to learn are how to enter matrices, how to use the : (colon) operator, and how to invoke functions. You will also get a brief overview of graphics and programming in MATLAB. After you master the basics, you can access the rest of the documentation through the online help (Help Desk) facility. I want to look at some There are numerous demonstrations included with MATLAB. samples of what you can do You can see the demos by selecting Examples and Demos from with MATLAB. the Help menu. (Linux users type demo at the MATLAB prompt.) There are demos in mathematics, graphics, visualization, and much more. You also will find a large selection of demos at Finding Reference InformationFinding Reference InformationWhat I Want What I Should DoI want to know how to use a Use the online help (Help Desk) facility, or, use the M-file helpspecific function. window to get brief online help. These are available using the command helpdesk or from the Help menu on the PC. The MATLAB Function Reference is also available on the Help Desk in PDF format (under Online Manuals) if you want to print out any of the function descriptions in high-quality form.I want to find a function for There are several choices:a specific purpose but I don'tknow its name. • Use lookfor (e.g., lookfor inverse) from the command line. • See Appendix A, "MATLAB Quick Reference," in this book for a list of MATLAB functions. • From the Help Desk peruse the MATLAB functions by Subject or by Index. • Use the full text search from the Help Desk.I want to learn about a Use the Help Desk facility to locate the appropriate chapter inspecific topic like sparse Using MATLAB.matrices, ordinarydifferential equations, or cellarrays.I want to know what Use the Help Desk facility to see the Function Referencefunctions are available in a grouped by subject, or see Appendix A, "MATLAB Quickgeneral area. Reference," in this book for a list of MATLAB functions. The Help Desk provides access to the reference pages for the hundreds of functions included with MATLAB.I want to learn about the See Chapter 6, "Symbolic Math Toolbox," and Appendix B,Symbolic Math Toolbox. "Symbolic Math Toolbox Quick Reference," in this book. For complete descriptions of the Symbolic Math Toolbox functions, use the Help Desk and select Symbolic Math Toolbox functions. 1-7 1 Introduction Troubleshooting and Other Resources What I Want What I Should Do I have a MATLAB specific Visit the Technical Support section problem I want help with. ( of the MathWorks Web site and use the Solution Support Engine to search the Knowledge Base of problem solutions. I want to report a bug or Use the Help Desk or send e-mail to [email protected] or make a suggestion. [email protected]. Documentation Library Your Student Version of MATLAB & Simulink contains much more documentation than the two printed books, Learning MATLAB and Learning Simulink. On your CD is a personal reference library of every book and reference page distributed by The MathWorks. Access this documentation library from the Help Desk. Note Even though you have the documentation set for the MathWorks family of products, not every product is available for the Student Version of MATLAB & Simulink. For an up-to-date list of available products, visit the MathWorks Store. At the store you can also purchase printed manuals for the MATLAB family of products. Accessing the Online Documentation Access the online documentation (Help Desk) directly from your product CD. (Linux users should refer to Chapter 2, "Installation," for specific information on configuring and accessing the Help Desk from the CD.) 1 Place the CD in your CD-ROM drive. 2 Select Documentation (Help Desk) from the Help menu. The Help Desk appears in a Web browser.1-8 Troubleshooting and Other ResourcesUsenet NewsgroupIf you have access to Usenet newsgroups, you can join the active community ofparticipants in the MATLAB specific group, comp.soft-sys.matlab. Thisforum is a gathering of professionals and students who use MATLAB and havequestions or comments about it and its associated products. This is a greatresource for posing questions and answering those of others. MathWorks staffalso participates actively in this newsgroup.MathWorks Web SiteUse your browser to visit the MathWorks Web site, You'llfind lots of information about MathWorks products and how they are used ineducation and industry, product demos, and MATLAB based books. From theWeb site you will also be able to access our technical support resources, view alibrary of user and company supplied M-files, and get information aboutproducts and upcoming events.MathWorks Education Web SiteThis education-specific Web site, containsmany resources for various branches of mathematics and science. Many ofthese include teaching examples, books, and other related products. You willalso find a comprehensive list of links to Web sites where MATLAB is used forteaching and research at universities.MATLAB Related BooksHundreds of MATLAB related books are available from many differentpublishers. An up-to-date list is available at StoreThe MathWorks Store ( gives you an easy way topurchase products, upgrades, and documentation. 1-9 1 Introduction MathWorks Knowledge Base You can access the MathWorks Knowledge Base from the Support link on our Web site. Our Technical Support group maintains this database of frequently asked questions (FAQ). You can peruse the Knowledge Base by topics, categories, or use the Solution Search Engine to quickly locate relevant data. You can answer many of your questions by spending a few minutes with this around-the-clock resource. Also, Technical Notes, which is accessible from our Technical Support Web site ( contains numerous examples on graphics, mathematics, API, Simulink, and others. Technical Support Registered users of the Student Version of MATLAB & Simulink can use our electronic technical support services to answer product questions. Visit our Technical Support Web site at Student Version Support Policy The MathWorks does not provide telephone technical support to users of the Student Version of MATLAB & Simulink. There are numerous other vehicles of technical support that you can use. The Sources of Information card included with the Student Version identifies the ways to obtain support. After checking the available MathWorks sources for help, if you still cannot resolve your problem, you should contact your instructor. Your instructor should be able to help you, but if not, there is telephone technical support for registered instructors who have adopted the Student Version of MATLAB & Simulink in their courses. Product Registration Visit the MathWorks Web site ( and register your Student Version.1-10 About MATLAB and SimulinkAbout MATLAB and Simulink What Is MATLAB? MATLAB is a high-performance language for technical computing. It integrates computation, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notation. Typical uses include: • Math and computation • Algorithm development • Modeling, simulation, and prototyping • Data analysis, exploration, and visualization • Scientific and engineering graphics • Application development, including graphical user interface building MATLAB is an interactive system whose basic data element is an array that does not require dimensioning. This allows you to solve many technical computing problems, especially those with matrix and vector formulations, in a fraction of the time it would take to write a program in a scalar noninteractive language such as C or Fortran. The name MATLAB stands for matrix laboratory. MATLAB was originally written to provide easy access to matrix software developed by the LINPACK and EISPACK projects, which together represent the state-of-the-art in software for matrix computation. MATLAB has evolved over a period of years with input from many users. In university environments, it is the standard instructional tool for introductory and advanced courses in mathematics, engineering, and science. In industry, MATLAB is the tool of choice for high-productivity research, development, and analysis. Toolboxes MATLAB features a family of application-specific solutions called toolboxes. Very important to most users of MATLAB, toolboxes allow you to learn and apply specialized technology. Toolboxes are comprehensive collections of MATLAB functions (M-files) that extend the MATLAB environment to solve particular classes of problems. Areas in which toolboxes are available include 1-11 1 Introduction signal processing, control systems, neural networks, fuzzy logic, wavelets, simulation, and many others. The MATLAB System The MATLAB system consists of five main parts: The MATLAB language. This is a high-level matrix/array language with control flow statements, functions, data structures, input/output, and object-oriented programming features. It allows both "programming in the small" to rapidly create quick and dirty throw-away programs, and "programming in the large" to create complete large and complex application programs. The MATLAB working environment. This is the set of tools and facilities that you work with as the MATLAB user or programmer. It includes facilities for managing the variables in your workspace and importing and exporting data. It also includes tools for developing, managing, debugging, and profiling M-files, MATLAB's applications. Handle Graphics®. This is the MATLAB graphics system. It includes high-level commands for two-dimensional and three-dimensional data visualization, image processing, animation, and presentation graphics. It also includes low-level commands that allow you to fully customize the appearance of graphics as well as to build complete graphical user interfaces on your MATLAB applications. The MATLAB mathematical function library. This is a vast collection of computational algorithms ranging from elementary functions like sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms. The MATLAB Application Program Interface (API). This is a library that allows you to write C and Fortran programs that interact with MATLAB. It include facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-files.1-12 About MATLAB and SimulinkWhat Is Simulink?Simulink, a companion program to MATLAB, is an interactive system forsimulating nonlinear dynamic systems. It is a graphical mouse-driven programthat allows you to model a system by drawing a block diagram on the screenand manipulating it dynamically. It can work with linear, nonlinear,continuous-time, discrete-time, multirate, and hybrid systems.Blocksets are add-ons to Simulink that provide additional libraries of blocks forspecialized applications like communications, signal processing, and powersystems.Real-Time Workshop® is a program that allows you to generate C code fromyour block diagrams and to run it on a variety of real-time systems. 1-13 Installing on a PCAdobe Acrobat Reader is required to view and print the MATLAB onlinedocumentation that is in PDF format. Adobe Acrobat Reader is available on theMATLAB CD.MEX-FilesMEX-files are dynamically linked subroutines that MATLAB canautomatically load and execute. They provide a mechanism by which you cancall your own C and Fortran subroutines from MATLAB as if they were built-infunctions.For More Information The Application Program Interface Guide describeshow to write MEX-files and the Application Program Interface Referencedescribes the collection of API functions. Both of these are available from theHelp Desk.If you plan to build your own MEX-files, one of the following is required:• DEC Visual Fortran version 5.0 or 6.0• Microsoft Visual C/C++ version 4.2, 5.0, or 6.0• Borland C++ version 5.0, 5.2, or 5.3• Watcom C/C++ version 10.6 or 11Note For an up-to-date list of all the compilers supported by MATLAB, seethe MathWorks Technical Support Department's Technical Notes at 2-3 2 Installation Installing MATLAB This list summarizes the steps in the standard installation procedure. You can perform the installation by simply following the instructions in the dialog boxes presented by the installation program; it walks you through this process. 1 Stop any virus protection software you have running. 2 Insert the MathWorks CD into your CD-ROM drive. The installation program starts automatically when the CD-ROM drive is ready. You can also run setup.exe from the CD. View the Welcome screen. 3 Review the Student Use Policy. 4 Review the Software License Agreement. 5 Enter your name and school name. 6 To install the complete set of software (MATLAB, Simulink, and the Symbolic Math Toolbox), make sure all of the components are selected in the Select MATLAB Components dialog box. 7 Specify the destination directory, that is, the directory where you want to save the files on your hard drive. To change directories, use the Browse button. 8 When the installation is complete, verify the installation by starting MATLAB and running one of the demo programs. 9 Customize any MATLAB environment options, if desired. For example, to include default definitions or any MATLAB expressions that you want executed every time MATLAB is invoked, create a file named startup.m in the $MATLABtoolboxlocal directory. MATLAB executes this file each time MATLAB is invoked. 1 Perform any additional necessary configuration by typing the appropriate 0 command at the MATLAB command prompt. For example, to configure the MATLAB Notebook, type notebook -setup. To configure a compiler to work with the MATLAB Application Program Interface, type mex -setup.2-4 Installing on a PCFor More Information The MATLAB Installation Guide for PC providesadditional installation information. This manual is available in PDF formfrom Online Manuals on the Help Desk.Installing Additional ToolboxesTo purchase additional toolboxes, visit the MathWorks Store at( Once you purchase a toolbox, it is downloaded toyour computer.When you download a toolbox, you receive an installation program for thetoolbox. To install the toolbox, run the installation program by double-clickingon its icon. After you successfully install the toolbox, all of its functionality willbe available to you when you start MATLAB.Note Some toolboxes have ReadMe files associated with them. When youdownload the toolbox, check to see if there is a ReadMe file. These files containimportant information about the toolbox and possibly installation andconfiguration notes. To view the ReadMe file for a toolbox, use the whatsnewcommand.Accessing the Online Documentation (Help Desk)Access the online documentation (Help Desk) directly from your product CD:1 Place the CD in your CD-ROM drive.2 Select Documentation (Help Desk) from the Help menu in the MATLAB command window. You can also type helpdesk at the MATLAB prompt. 2-5 2 Installation The Help Desk, similar to this figure, appears in your Web browser.2-6 Installing on LinuxInstalling on Linux System Requirements Note For the most up-to-date information about system requirements, see the system requirements page, available in the products area at the MathWorks Web site ( MATLAB and Simulink • Intel-based Pentium, Pentium Pro, or Pentium II personal computer • Linux 2.0.34 kernel (Red Hat 4.2, 5.1, Debian 2.0) • X Windows (X11R6) • 60 MB free disk space for MATLAB & Simulink • 64 MB memory, additional memory strongly recommended • 64 MB swap space (recommended) • CD-ROM drive (for installation and online documentation) • 8-bit graphics adapter and display (for 256 simultaneous colors) • Netscape Navigator 3.0 or higher (to view the online documentation) Adobe Acrobat Reader is required to view and print the MATLAB online documentation that is in PDF format. Adobe Acrobat Reader is available on the MATLAB CD. MEX-Files MEX-files are dynamically linked subroutines that MATLAB can automatically load and execute. They provide a mechanism by which you can call your own C and Fortran subroutines from MATLAB as if they were built-in functions. 2-7 2 Installation For More Information The Application Program Interface Guide describes how to write MEX-files and the Application Program Interface Reference describes the collection of API functions. Both of these are available from the Help Desk. If you plan to build your own MEX-files, you need an ANSIC C compiler (e.g., the GNU C compiler, gcc). Note For an up-to-date list of all the compilers supported by MATLAB, see the MathWorks Technical Support Department's Technical Notes at Installing MATLAB The following instructions describe how to install the Student Version of MATLAB & Simulink on your computer. Note It is recommended that you log in as root to perform your installation. Installing the Software To install the Student Version: 1 If your CD-ROM drive is not accessible to your operating system, you will need to create a directory to be the mount point for it. mkdir /cdrom 2 Place the CD into the CD-ROM drive.2-8 Installing on Linux3 Execute the command to mount the CD-ROM drive on your system. For example, # mount -t iso9660 /dev/cdrom /cdrom should work on most systems. If your /etc/fstab file has a line similar to /dev/cdrom /cdrom iso9660 noauto,ro,user,exec 0 0 then nonroot users can mount the CD-ROM using the simplified command $ mount /cdromNote If the exec option is missing (as it often is by default, for securityreasons), you will receive a "Permission denied" error when attempting to runthe install script. To remedy this, either use the full mount command shownabove (as root) or add the exec option to the file /etc/fstab.4 Move to the installation location using the cd command. For example, if you are going to install into the location /usr/local/matlab5, use the commands cd /usr/local mkdir matlab5 cd matlab5 Subsequent instructions in this section refer to this directory as $MATLAB.5 Copy the license file, license.dat, from the CD to $MATLAB.6 Run the CD install script. /cdrom/install_lnx86.sh The welcome screen appears. Select OK to proceed with the installation.Note If you need additional help on any step during this installation process,click the Help button at the bottom of the dialog box. 2-9 2 Installation 7 Accept or reject the software licensing agreement displayed. If you accept the terms of the agreement, you may proceed with the installation. 8 The MATLAB Root Directory screen is displayed. Select OK if the pathname for the MATLAB root directory is correct; otherwise, change it to the desired location. 9 The system displays your license file. Press OK.2-10 Installing on Linux10 The installation program displays the Product Installation Options screen, which is similar to this. The products you are licensed to install are listed in the Items to install list box. The right list box displays the products that you do not want to install. To install the complete Student Version of MATLAB & Simulink, you must install all the products for which you are licensed (MATLAB, MATLAB Toolbox, MATLAB Kernel, Simulink, Symbolic Math, Symbolic Math Library, and GhostScript). Select OK. 2-11 2 Installation 1 The installation program displays the Installation Data screen. 1 Specify the directory location in your file system for symbolic links to the matlab, matlabdoc, and mex scripts. Choose a directory such as /usr/local/bin. You must be logged in as root to do this. In the MATLAB License No. field, enter student. Select OK to continue. 1 The Begin Installation screen is displayed. Select OK to start the 2 installation. After the installation is complete, the Installation Complete screen is displayed, assuming your installation is successful. Select Exit to exit from the setup program. 1 If desired, customize any MATLAB environment options. For example, to 3 include default definitions or any MATLAB expressions that you want executed every time MATLAB is invoked, create a file named startup.m in the $MATLAB/toolbox/local directory. MATLAB executes this file each time MATLAB is invoked. 1 You must edit the docopt.m M-file located in the $MATLAB/toolbox/local 4 directory to specify the path to the online documentation (Help Desk). For example, if /cdrom is the path to your CD-ROM drive, then you would use2-12 Installing on Linux /cdrom/help. To set the path using this example, change the lines in the if isunix block in the docopt.m file to if isunix % UNIX % doccmd = ; % options = ; docpath = /cdrom/help; The docopt.m file also allows you to specify an alternative Web browser or additional initial browser options. It is configured for Netscape Navigator.15 Start MATLAB by entering the matlab command. If you did not set up symbolic links in a directory on your path, type $MATLAB/bin/matlab.Post Installation ProceduresSuccessful InstallationIf you want to use the MATLAB Application Program Interface, you mustconfigure the mex script to work with your compiler. Also, some toolboxes mayrequire some additional configuration. For more information, see "InstallingAdditional Toolboxes" later in this section.Unsuccessful InstallationIf MATLAB does not execute correctly after installation:1 Check the MATLAB Known Software and Documentation Problems document for the latest information concerning installation. This document is accessible from the Help Desk.2 Repeat the installation procedure from the beginning but run the CD install script using the -t option. /cdrom/install_lnx86.sh -tFor More Information The MATLAB Installation Guide for UNIX providesadditional installation information. This manual is available in PDF formfrom Online Manuals on the Help Desk. 2-13 2 Installation Installing Additional Toolboxes To purchase additional toolboxes, visit the MathWorks Store at ( Once you purchase a toolbox, it is downloaded to your computer. When you download a toolbox on Linux, you receive a tar file (a standard, compressed formatted file). To install the toolbox, you must: 1 Place the tar file in $MATLAB and un-tar it. tar -xf filename 2 Run install_matlab. After you successfully install the toolbox, all of its functionality will be available to you when you start MATLAB. Note Some toolboxes have ReadMe files associated with them. When you download the toolbox, check to see if there is a ReadMe file. These files contain important information about the toolbox and possibly installation and configuration notes. To view the ReadMe file for a toolbox, use the whatsnew command. Accessing the Online Documentation (Help Desk) Access the online documentation (Help Desk) directly from your product CD: 1 Place the CD in your CD-ROM drive and mount it. 2 Type helpdesk at the MATLAB prompt.2-14 Installing on LinuxThe Help Desk, similar to this figure, appears in your Web browser. 2-15 3 Getting Started Starting MATLAB This book is intended to help you start learning MATLAB. It contains a number of examples, so you should run MATLAB and follow along. To run MATLAB on a PC, double-click on the MATLAB icon. To run MATLAB on a Linux system, type matlab at the operating system prompt. To quit MATLAB at any time, type quit at the MATLAB prompt. If you feel you need more assistance, you can: • Access the Help Desk by typing helpdesk at the MATLAB prompt. • Type help at the MATLAB prompt. • Pull down the Help menu on a PC. For more information about help and online documentation, see "Help and Online Documentation" later in this chapter. Also, Chapter 1 provides additional help resources.3-2 Matrices and Magic SquaresMatrices and Magic Squares The best way for you to get started with MATLAB is to learn how to handle matrices. This section shows you how to do that. In MATLAB, a matrix is a rectangular array of numbers. Special meaning is sometimes attached to 1-by-1 matrices, which are scalars, and to matrices with only one row or column, which are vectors. MATLAB has other ways of storing both numeric and nonnumeric data, but in the beginning, it is usually best to think of everything as a matrix. The operations in MATLAB are designed to be as natural as possible. Where other programming languages work with numbers one at a time, MATLAB allows you to work with entire matrices quickly and easily. 3-3 3 Getting Started A good example matrix, used throughout this book, appears in the Renaissance engraving Melancholia I by the German artist and amateur mathematician Albrecht Dürer. This image is filled with mathematical symbolism, and if you look carefully, you will see a matrix in the upper right corner. This matrix is known as a magic square and was believed by many in Dürer's time to have genuinely magical properties. It does turn out to have some fascinating characteristics worth exploring. Entering Matrices You can enter matrices into MATLAB in several different ways: • Enter an explicit list of elements. • Load matrices from external data files. • Generate matrices using built-in functions. • Create matrices with your own functions in M-files. Start by entering Dürer's matrix as a list of its elements. You have only to follow a few basic conventions: • Separate the elements of a row with blanks or commas. • Use a semicolon, ; , to indicate the end of each row. • Surround the entire list of elements with square brackets, [ ]. To enter Dürer's matrix, simply type A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]3-4 Matrices and Magic SquaresMATLAB displays the matrix you just entered, A = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1This exactly matches the numbers in the engraving. Once you have entered thematrix, it is automatically remembered in the MATLAB workspace. You canrefer to it simply as A. Now that you have A in the workspace, take a look atwhat makes it so interesting. Why is it magic?sum, transpose, and diagYou're probably already aware that the special properties of a magic squarehave to do with the various ways of summing its elements. If you take the sumalong any row or column, or along either of the two main diagonals, you willalways get the same number. Let's verify that using MATLAB. The firststatement to try is sum(A)MATLAB replies with ans = 34 34 34 34When you don't specify an output variable, MATLAB uses the variable ans,short for answer, to store the results of a calculation. You have computed a rowvector containing the sums of the columns of A. Sure enough, each of thecolumns has the same sum, the magic sum, 34.How about the row sums? MATLAB has a preference for working with thecolumns of a matrix, so the easiest way to get the row sums is to transpose thematrix, compute the column sums of the transpose, and then transpose theresult. The transpose operation is denoted by an apostrophe or single quote, .It flips a matrix about its main diagonal and it turns a row vector into a columnvector. So A 3-5 Matrices and Magic SquaresThe other diagonal, the so-called antidiagonal, is not so importantmathematically, so MATLAB does not have a ready-made function for it. But afunction originally intended for use in graphics, fliplr, flips a matrix from leftto right. sum(diag(fliplr(A))) ans = 34You have verified that the matrix in Dürer's engraving is indeed a magicsquare and, in the process, have sampled a few MATLAB matrix operations.The following sections continue to use this matrix to illustrate additionalMATLAB capabilities.SubscriptsThe element in row i and column j of A is denoted by A(i,j). For example,A(4,2) is the number in the fourth row and second column. For our magicsquare, A(4,2) is 15. So it is possible to compute the sum of the elements in thefourth column of A by typing A(1,4) + A(2,4) + A(3,4) + A(4,4)This produces ans = 34but is not the most elegant way of summing a single column.It is also possible to refer to the elements of a matrix with a single subscript,A(k). This is the usual way of referencing row and column vectors. But it canalso apply to a fully two-dimensional matrix, in which case the array isregarded as one long column vector formed from the columns of the originalmatrix. So, for our magic square, A(8) is another way of referring to the value15 stored in A(4,2).If you try to use the value of an element outside of the matrix, it is an error. t = A(4,5) Index exceeds matrix dimensions. 3-7 3 Getting Started On the other hand, if you store a value in an element outside of the matrix, the size increases to accommodate the newcomer. X = A; X(4,5) = 17 X = 16 3 2 13 0 5 10 11 8 0 9 6 7 12 0 4 15 14 1 17 The Colon Operator The colon, :, is one of MATLAB's most important operators. It occurs in several different forms. The expression 1:10 is a row vector containing the integers from 1 to 10 1 2 3 4 5 6 7 8 9 10 To obtain nonunit spacing, specify an increment. For example, 100:-7:50 is 100 93 86 79 72 65 58 51 and 0:pi/4:pi is 0 0.7854 1.5708 2.3562 3.1416 Subscript expressions involving colons refer to portions of a matrix. A(1:k,j) is the first k elements of the jth column of A. So sum(A(1:4,4))3-8 Matrices and Magic Squares computes the sum of the fourth column. But there is a better way. The colon by itself refers to all the elements in a row or column of a matrix and the keyword end refers to the last row or column. So sum(A(:,end)) computes the sum of the elements in the last column of A. ans = 34 Why is the magic sum for a 4-by-4 square equal to 34? If the integers from 1 to 16 are sorted into four groups with equal sums, that sum must be sum(1:16)/4 which, of course, is ans = 34Using the Symbolic Math The magic FunctionToolbox, you can discover MATLAB actually has a built-in function that creates magic squares of almostthat the magic sum for an any size. Not surprisingly, this function is named magic.n-by-n magic square is(n 3 + n )/2. B = magic(4) B = 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1 This matrix is almost the same as the one in the Dürer engraving and has all the same "magic" properties; the only difference is that the two middle columns are exchanged. To make this B into Dürer's A, swap the two middle columns. A = B(:,[1 3 2 4]) 3-9 3 Getting Started This says "for each of the rows of matrix B, reorder the elements in the order 1, 3, 2, 4." It produces A = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 Why would Dürer go to the trouble of rearranging the columns when he could have used MATLAB's ordering? No doubt he wanted to include the date of the engraving, 1514, at the bottom of his magic square. For More Information Using MATLAB provides comprehensive material on the MATLAB language, environment, mathematical topics, and programming in MATLAB. Access Using MATLAB from the Help Desk.3-10 ExpressionsExpressions Like most other programming languages, MATLAB provides mathematical expressions, but unlike most programming languages, these expressions involve entire matrices. The building blocks of expressions are: • Variables • Numbers • Operators • Functions Variables MATLAB does not require any type declarations or dimension statements. When MATLAB encounters a new variable name, it automatically creates the variable and allocates the appropriate amount of storage. If the variable already exists, MATLAB changes its contents and, if necessary, allocates new storage. For example, num_students = 25 creates a 1-by-1 matrix named num_students and stores the value 25 in its single element. Variable names consist of a letter, followed by any number of letters, digits, or underscores. MATLAB uses only the first 31 characters of a variable name. MATLAB is case sensitive; it distinguishes between uppercase and lowercase letters. A and a are not the same variable. To view the matrix assigned to any variable, simply enter the variable name. Numbers MATLAB uses conventional decimal notation, with an optional decimal point and leading plus or minus sign, for numbers. Scientific notation uses the letter e to specify a power-of-ten scale factor. Imaginary numbers use either i or j as a suffix. Some examples of legal numbers are 3 -99 0.0001 9.6397238 1.60210e-20 6.02252e23 1i -3.14159j 3e5i 3-11 3 Getting Started All numbers are stored internally using the long format specified by the IEEE floating-point standard. Floating-point numbers have a finite precision of roughly 16 significant decimal digits and a finite range of roughly 10-308 to 10+308. Operators Expressions use familiar arithmetic operators and precedence rules. + Addition - Subtraction * Multiplication / Division Left division (described in "Matrices and Linear Algebra" in Using MATLAB) ^ Power Complex conjugate transpose ( ) Specify evaluation order Functions MATLAB provides a large number of standard elementary mathematical functions, including abs, sqrt, exp, and sin. Taking the square root or logarithm of a negative number is not an error; the appropriate complex result is produced automatically. MATLAB also provides many more advanced mathematical functions, including Bessel and gamma functions. Most of these functions accept complex arguments. For a list of the elementary mathematical functions, type help elfun3-12 ExpressionsFor a list of more advanced mathematical and matrix functions, type help specfun help elmatFor More Information Appendix A, "MATLAB Quick Reference," containsbrief descriptions of the MATLAB functions. Use the Help Desk to accesscomplete descriptions of all the MATLAB functions by Subject or by Index.Some of the functions, like sqrt and sin, are built-in. They are part of theMATLAB core so they are very efficient, but the computational details are notreadily accessible. Other functions, like gamma and sinh, are implemented inM-files. You can see the code and even modify it if you want.Several special functions provide values of useful constants. pi 3.14159265… i Imaginary unit, √-1 j Same as i eps Floating-point relative precision, 2-52 realmin Smallest floating-point number, 2-1022 realmax Largest floating-point number, (2-ε)21023 Inf Infinity NaN Not-a-numberInfinity is generated by dividing a nonzero value by zero, or by evaluating welldefined mathematical expressions that overflow, i.e., exceed realmax.Not-a-number is generated by trying to evaluate expressions like 0/0 orInf-Inf that do not have well defined mathematical values.The function names are not reserved. It is possible to overwrite any of themwith a new variable, such as eps = 1.e-6 3-13 3 Getting Started and then use that value in subsequent calculations. The original function can be restored with clear eps Expressions You have already seen several examples of MATLAB expressions. Here are a few more examples, and the resulting values. rho = (1+sqrt(5))/2 rho = 1.6180 a = abs(3+4i) a = 5 z = sqrt(besselk(4/3,rho-i)) z = 0.3730+ 0.3214i huge = exp(log(realmax)) huge = 1.7977e+308 toobig = pi*huge toobig = Inf3-14 3 Getting Started The load Command The load command reads binary files containing matrices generated by earlier MATLAB sessions, or reads text files containing numeric data. The text file should be organized as a rectangular table of numbers, separated by blanks, with one row per line, and an equal number of elements in each row. For example, outside of MATLAB, create a text file containing these four lines. 16.0 3.0 2.0 13.0 5.0 10.0 11.0 8.0 9.0 6.0 7.0 12.0 4.0 15.0 14.0 1.0 Store the file under the name magik.dat. Then the command load magik.dat reads the file and creates a variable, magik, containing our example matrix. M-Files You can create your own matrices using M-files, which are text files containing MATLAB code. Just create a file containing the same statements you would type at the MATLAB command line. Save the file under a name that ends in .m. Note To access a text editor on a PC, choose Open or New from the File menu or press the appropriate button on the toolbar. To access a text editor under Linux, use the ! symbol followed by whatever command you would ordinarily use at your operating system prompt. For example, create a file containing these five lines. A = [ ... 16.0 3.0 2.0 13.0 5.0 10.0 11.0 8.0 9.0 6.0 7.0 12.0 4.0 15.0 14.0 1.0 ];3-16 3 Getting Started Deleting Rows and Columns You can delete rows and columns from a matrix using just a pair of square brackets. Start with X = A; Then, to delete the second column of X, use X(:,2) = [] This changes X to X = 16 2 13 5 11 8 9 7 12 4 14 1 If you delete a single element from a matrix, the result isn't a matrix anymore. So, expressions like X(1,2) = [] result in an error. However, using a single subscript deletes a single element, or sequence of elements, and reshapes the remaining elements into a row vector. So X(2:2:10) = [] results in X = 16 9 2 7 13 12 13-18 More About Matrices and ArraysMore About Matrices and Arrays This sections shows you more about working with matrices and arrays, focusing on: • Linear algebra • Arrays • Multivariate data Linear Algebra Informally, the terms matrix and array are often used interchangeably. More precisely, a matrix is a two-dimensional numeric array that represents a linear transformation. The mathematical operations defined on matrices are the subject of linear algebra. Dürer's magic square A = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 provides several examples that give a taste of MATLAB matrix operations. You've already seen the matrix transpose, A. Adding a matrix to its transpose produces a symmetric matrix. A + A ans = 32 8 11 17 8 20 17 23 11 17 14 26 17 23 26 2 For More Information All of the MATLAB math functions are described in the MATLAB Function Reference, which is accessible from the Help Desk. 3-19 3 Getting Started The multiplication symbol, *, denotes the matrix multiplication involving inner products between rows and columns. Multiplying the transpose of a matrix by the original matrix also produces a symmetric matrix. A*A ans = 378 212 206 360 212 370 368 206 206 368 370 212 360 206 212 378 The determinant of this particular matrix happens to be zero, indicating that the matrix is singular. d = det(A) d = 0 The reduced row echelon form of A is not the identity. R = rref(A) R = 1 0 0 1 0 1 0 -3 0 0 1 3 0 0 0 0 Since the matrix is singular, it does not have an inverse. If you try to compute the inverse with X = inv(A) you will get a warning message Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 1.175530e-017. Roundoff error has prevented the matrix inversion algorithm from detecting exact singularity. But the value of rcond, which stands for reciprocal condition estimate, is on the order of eps, the floating-point relative precision, so the computed inverse is unlikely to be of much use.3-20 3 Getting Started Such matrices represent the transition probabilities in a Markov process. Repeated powers of the matrix represent repeated steps of the process. For our example, the fifth power P^5 is 0.2507 0.2495 0.2494 0.2504 0.2497 0.2501 0.2502 0.2500 0.2500 0.2498 0.2499 0.2503 0.2496 0.2506 0.2505 0.2493 This shows that as k approaches infinity, all the elements in the kth power, Pk, approach 1/4. Finally, the coefficients in the characteristic polynomial poly(A) are 1 -34 -64 2176 0 This indicates that the characteristic polynomial det( A - λI ) is λ4 - 34λ3 - 64λ2 + 2176λ The constant term is zero, because the matrix is singular, and the coefficient of the cubic term is -34, because the matrix is magic! Arrays When they are taken away from the world of linear algebra, matrices become two dimensional numeric arrays. Arithmetic operations on arrays are done element-by-element. This means that addition and subtraction are the same for arrays and matrices, but that multiplicative operations are different. MATLAB uses a dot, or decimal point, as part of the notation for multiplicative array operations.3-22 More About Matrices and ArraysAs an example, consider a data set with three variables:• Heart rate• Weight• Hours of exercise per weekFor five observations, the resulting array might look like D = 72 134 3.2 81 201 3.5 69 156 7.1 82 148 2.4 75 170 1.2The first row contains the heart rate, weight, and exercise hours for patient 1,the second row contains the data for patient 2, and so on. Now you can applymany of MATLAB's data analysis functions to this data set. For example, toobtain the mean and standard deviation of each column: mu = mean(D), sigma = std(D) mu = 75.8 161.8 3.48 sigma = 5.6303 25.499 2.2107For a list of the data analysis functions available in MATLAB, type help datafunIf you have access to the Statistics Toolbox, type help statsScalar ExpansionMatrices and scalars can be combined in several different ways. For example,a scalar is subtracted from a matrix by subtracting it from each element. Theaverage value of the elements in our magic square is 8.5, so B = A - 8.5 3-25 3 Getting Started forms a matrix whose column sums are zero. B = 7.5 -5.5 -6.5 4.5 -3.5 1.5 2.5 -0.5 0.5 -2.5 -1.5 3.5 -4.5 6.5 5.5 -7.5 sum(B) ans = 0 0 0 0 With scalar expansion, MATLAB assigns a specified scalar to all indices in a range. For example, B(1:2,2:3) = 0 zeros out a portion of B B = 7.5 0 0 4.5 -3.5 0 0 -0.5 0.5 -2.5 -1.5 3.5 -4.5 6.5 5.5 -7.5 Logical Subscripting The logical vectors created from logical and relational operations can be used to reference subarrays. Suppose X is an ordinary matrix and L is a matrix of the same size that is the result of some logical operation. Then X(L) specifies the elements of X where the elements of L are nonzero. This kind of subscripting can be done in one step by specifying the logical operation as the subscripting expression. Suppose you have the following set of data. x = 2.1 1.7 1.6 1.5 NaN 1.9 1.8 1.5 5.1 1.8 1.4 2.2 1.6 1.8 The NaN is a marker for a missing observation, such as a failure to respond to an item on a questionnaire. To remove the missing data with logical indexing,3-26 More About Matrices and Arraysuse finite(x), which is true for all finite numerical values and false for NaNand Inf. x = x(finite(x)) x = 2.1 1.7 1.6 1.5 1.9 1.8 1.5 5.1 1.8 1.4 2.2 1.6 1.8Now there is one observation, 5.1, which seems to be very different from theothers. It is an outlier. The following statement removes outliers, in this casethose elements more than three standard deviations from the mean. x = x(abs(x-mean(x)) <= 3*std(x)) x = 2.1 1.7 1.6 1.5 1.9 1.8 1.5 1.8 1.4 2.2 1.6 1.8For another example, highlight the location of the prime numbers in Dürer'smagic square by using logical indexing and scalar expansion to set thenonprimes to 0. A(~isprime(A)) = 0 A = 0 3 2 13 5 0 11 0 0 0 7 0 0 0 0 0The find FunctionThe find function determines the indices of array elements that meet a givenlogical condition. In its simplest form, find returns a column vector of indices.Transpose that vector to obtain a row vector of indices. For example, k = find(isprime(A))picks out the locations, using one-dimensional indexing, of the primes in themagic square. k = 2 5 9 10 11 13 3-27 The Command WindowThe Command Window So far, you have been using the MATLAB command line, typing commands and expressions, and seeing the results printed in the command window. This section describes a few ways of altering the appearance of the command window. If your system allows you to select the command window font or typeface, we recommend you use a fixed width font, such as Fixedsys or Courier, to provide proper spacing. The format Command The format command controls the numeric format of the values displayed by MATLAB. The command affects only how numbers are displayed, not how MATLAB computes or saves them. Here are the different formats, together with the resulting output produced from a vector x with components of different magnitudes. x = [4/3 1.2345e-6] format short 1.3333 0.0000 format short e 1.3333e+000 1.2345e-006 format short g 1.3333 1.2345e-006 format long 1.33333333333333 0.00000123450000 format long e 1.333333333333333e+000 1.234500000000000e-006 3-29 3 Getting Started format long g 1.33333333333333 1.2345e-006 format bank 1.33 0.00 format rat 4/3 1/810045 format hex 3ff5555555555555 3eb4b6231abfd271 If the largest element of a matrix is larger than 103 or smaller than 10-3, MATLAB applies a common scale factor for the short and long formats. In addition to the format commands shown above format compact suppresses many of the blank lines that appear in the output. This lets you view more information on a screen or window. If you want more control over the output format, use the sprintf and fprintf functions. Suppressing Output If you simply type a statement and press Return or Enter, MATLAB automatically displays the results on screen. However, if you end the line with a semicolon, MATLAB performs the computation but does not display any output. This is particularly useful when you generate large matrices. For example, A = magic(100);3-30 The Command WindowLong Command LinesIf a statement does not fit on one line, use three periods, ..., followed byReturn or Enter to indicate that the statement continues on the next line. Forexample, s = 1 -1/2 + 1/3 -1/4 + 1/5 - 1/6 + 1/7 ... - 1/8 + 1/9 - 1/10 + 1/11 - 1/12;Blank spaces around the =, +, and - signs are optional, but they improvereadability.Command Line EditingVarious arrow and control keys on your keyboard allow you to recall, edit, andreuse commands you have typed earlier. For example, suppose you mistakenlyenter rho = (1 + sqt(5))/2You have misspelled sqrt. MATLAB responds with Undefined function or variable sqt.Instead of retyping the entire line, simply press the ↑ key. The misspelledcommand is redisplayed. Use the ← key to move the cursor over and insert themissing r. Repeated use of the ↑ key recalls earlier lines. Typing a fewcharacters and then the ↑ key finds a previous line that begins with thosecharacters.The list of available command line editing keys is different on differentcomputers. Experiment to see which of the following keys is available on yourmachine. (Many of these keys will be familiar to users of the EMACS editor.) ↑ Ctrl-p Recall previous line ↓ Ctrl-n Recall next line ← Ctrl-b Move back one character → Ctrl-f Move forward one character → Ctrl-→ Ctrl-r Move right one word 3-31 3 Getting Started ← Ctrl-← Ctrl-l Move left one word Home Ctrl-a Move to beginning of line End Ctrl-e Move to end of line Esc Ctrl-u Clear line Del Ctrl-d Delete character at cursor Backspace Ctrl-h Delete character before cursor Ctrl-k Delete to end of line3-32 The MATLAB EnvironmentThe MATLAB Environment The MATLAB environment includes both the set of variables built up during a MATLAB session and the set of disk files containing programs and data that persist between sessions. The Workspace The workspace is the area of memory accessible from the MATLAB command line. Two commands, who and whos, show the current contents of the workspace. The who command gives a short list, while whos also gives size and storage information. Here is the output produced by whos on a workspace containing results from some of the examples in this book. It shows several different MATLAB data structures. As an exercise, you might see if you can match each of the variables with the code segment in this book that generates it. whos Name Size Bytes Class A 4x4 128 double array D 5x3 120 double array M 10x1 3816 cell array S 1x3 442 struct array h 1x11 22 char array n 1x1 8 double array s 1x5 10 char array v 2x5 20 char array Grand total is 471 elements using 4566 bytes. To delete all the existing variables from the workspace, enter clear 3-33 3 Getting Started save Commands The save commands preserve the contents of the workspace in a MAT-file that can be read with the load command in a later MATLAB session. For example, save August17th saves the entire workspace contents in the file August17th.mat. If desired, you can save only certain variables by specifying the variable names after the filename. Ordinarily, the variables are saved in a binary format that can be read quickly (and accurately) by MATLAB. If you want to access these files outside of MATLAB, you may want to specify an alternative format. -ascii Use 8-digit text format. -ascii -double Use 16-digit text format. -ascii -double -tabs Delimit array elements with tabs. -v4 Create a file for MATLAB version 4. -append Append data to an existing MAT-file. When you save workspace contents in text format, you should save only one variable at a time. If you save more than one variable, MATLAB will create the text file, but you will be unable to load it easily back into MATLAB. The Search Path MATLAB uses a search path, an ordered list of directories, to determine how to execute the functions you call. When you call a standard function, MATLAB executes the first M-file function on the path that has the specified name. You can override this behavior using special private directories and subfunctions. The command path shows the search path on any platform. On PCs, choose Set Path from the File menu to view or modify the path.3-34 The MATLAB EnvironmentDisk File ManipulationThe commands dir, type, delete, and cd implement a set of generic operatingsystem commands for manipulating files. This table indicates how thesecommands map to other operating systems. MATLAB MS-DOS Linux dir dir ls type type cat delete del or erase rm cd chdir cdFor most of these commands, you can use pathnames, wildcards, and drivedesignators in the usual way.The diary CommandThe diary command creates a diary of your MATLAB session in a disk file. Youcan view and edit the resulting text file using any word processor. To create afile called diary that contains all the commands you enter, as well asMATLAB's printed output (but not the graphics output), enter diaryTo save the MATLAB session in a file with a particular name, use diary filenameTo stop recording the session, use diary offRunning External ProgramsThe exclamation point character ! is a shell escape and indicates that the restof the input line is a command to the operating system. This is quite useful forinvoking utilities or running other programs without quitting MATLAB. OnLinux, for example, !emacs magik.m 3-35 3 Getting Started invokes an editor called emacs for a file named magik.m. When you quit the external program, the operating system returns control to MATLAB.3-36 Help and Online DocumentationHelp and Online Documentation There are several different ways to access online information about MATLAB functions: • The MATLAB Help Desk • Online reference pages • The help command • Link to The MathWorks, Inc. The Help Desk The MATLAB Help Desk provides access to a wide range of help and reference information stored on CD. Many of the underlying documents use HyperText Markup Language (HTML) and are accessed with an Internet Web browser such as Netscape or Microsoft Explorer. The Help Desk process can be started on PCs by selecting the Help Desk option under the Help menu, or, on all computers, by typing helpdesk All of MATLAB's operators and functions have online reference pages in HTML format, which you can reach from the Help Desk. These pages provide more details and examples than the basic help entries. HTML versions of other documents, including this manual, are also available. A search engine, running on your own machine, can query all the online reference material. 3-37 3 Getting Started Using the Help Desk When you access the Help Desk, you see its entry screen. MATLAB Function Simulink instruction In-depth instruction Reference pages and reference pages on Simulink blocks Symbolic Math Toolbox Introduction to reference pages MATLAB Access all toolbox In-depth instruction documentation on MATLAB In-depth instruction on MATLAB graphics Access other product documentation Find answers to your questions (WWW) A particular MATLAB Contact the Function Reference MathWorks (WWW) page Search all documents Access all documents for particular text in PDF format Online Reference Pages The doc Command If you know the name of a specific function, you can view its reference page directly. For example, to get the reference page for the eval function, type doc eval3-38 Help and Online DocumentationThe doc command starts your Web browser, if it is not already running.Printing Online Reference PagesVersions of the online reference pages, as well as the rest of the MATLABdocumentation set, are also available in Portable Document Format (PDF)through the Help Desk. These pages are processed by Adobe's Acrobat reader.They reproduce the look and feel of the printed page, complete with fonts,graphics, formatting, and images. This is the best way to get printed copies ofreference material. To access the PDF versions of the books, select OnlineManuals from the Help Desk and then choose the desired book.The help CommandThe help command is the most basic way to determine the syntax and behaviorof a particular function. Information is displayed directly in the commandwindow. For example, help magicprints MAGIC Magic square. MAGIC(N) is an N-by-N matrix constructed from the integers 1 through N^2 with equal row, column, and diagonal sums. Produces valid magic squares for N = 1,3,4,5....Note MATLAB online help entries use uppercase characters for the functionand variable names to make them stand out from the rest of the text. Whentyping function names, however, always use the corresponding lowercasecharacters because MATLAB is case sensitive and all function names areactually in lowercase.All the MATLAB functions are organized into logical groups, and MATLAB'sdirectory structure is based on this grouping. For example, all the linear 3-39 3 Getting Started algebra functions reside in the matfun directory. To list the names of all the functions in that directory, with a brief description of each help matfun Matrix functions - numerical linear algebra. Matrix analysis. norm - Matrix or vector norm. normest - Estimate the matrix 2-norm ... The command help by itself lists all the directories, with a description of the function category each represents. matlab/general matlab/ops ... The lookfor Command The lookfor command allows you to search for functions based on a keyword. It searches through the first line of help text, which is known as the H1 line, for each MATLAB function, and returns the H1 lines containing a specified keyword. For example, MATLAB does not have a function named inverse. So the response from help inverse is inverse.m not found. But lookfor inverse3-40 Help and Online Documentationfinds over a dozen matches. Depending on which toolboxes you have installed,you will find entries like INVHILB Inverse Hilbert matrix. ACOSH Inverse hyperbolic cosine. ERFINV Inverse of the error function. INV Matrix inverse. PINV Pseudoinverse. IFFT Inverse discrete Fourier transform. IFFT2 Two-dimensional inverse discrete Fourier transform. ICCEPS Inverse complex cepstrum. IDCT Inverse discrete cosine transform.Adding -all to the lookfor command, as in lookfor -allsearches the entire help entry, not just the H1 line.Link to the MathWorksIf your computer is connected to the Internet, the Help Desk provides aconnection to The MathWorks, the home of MATLAB. You can also use theSolution Search Engine at The MathWorks Web site to query an up-to-datedata base of technical support information. 3-41 4 Graphics Basic Plotting MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as annotating and printing these graphs. This section describes a few of the most important graphics functions and provides examples of some typical applications. For More Information Using MATLAB Graphics provides in-depth coverage of MATLAB graphics and visualization tools. Access Using MATLAB Graphics from the Help Desk. Creating a Plot The plot function has different forms, depending on the input arguments. If y is a vector, plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x. For example, these statements use the colon operator to create a vector of x values ranging from zero to 2π, compute the sine of these values, and plot the result. x = 0:pi/100:2*pi; y = sin(x); plot(x,y) Now label the axes and add a title. The characters pi create the symbol π. xlabel(x = 0:2pi) ylabel(Sine of x) title(Plot of the Sine Function,FontSize,12)4-2 4 Graphics 1 sin(x) sin(x−.25) 0.8 sin(x−.5) 0.6 0.4 0.2 0 −0.2 −0.4 −0.6 −0.8 −1 0 1 2 3 4 5 6 7 For More Information See "Defining the Color of Lines for Plotting" in the Axes Properties chapter of Using MATLAB Graphics. Access Using MATLAB Graphics from the Help Desk. Specifying Line Styles and Colors It is possible to specify color, line styles, and markers (such as plus signs or circles) with the syntax plot(x,y,color_style_marker) color_style_marker is a string containing from one to four characters (enclosed in single quotation marks) constructed from a color, a line style, and a marker type:4-4 Basic Plotting• Color strings are c, m, y, r, g, b, w, and k. These correspond to cyan, magenta, yellow, red, green, blue, white, and black.• Linestyle strings are - for solid, -- for dashed, : for dotted, -. for dash-dot, and none for no line.• The marker types are +, o, *, and x and the filled marker types s for square, d for diamond, ^ for up triangle, v for down triangle, > for right triangle, < for left triangle, p for pentagram, h for hexagram, and none for no marker.Plotting Lines and MarkersIf you specify a marker type but not a linestyle, MATLAB draws only themarker. For example, plot(x,y,ks)plots black squares at each data point, but does not connect the markers witha line.The statement plot(x,y,r:+)plots a red dotted line and places plus sign markers at each data point. Youmay want to use fewer data points to plot the markers than you use to plot thelines. This example plots the data twice using a different number of points forthe dotted line and marker plots. x1 = 0:pi/100:2*pi; x2 = 0:pi/10:2*pi; plot(x1,sin(x1),r:,x2,sin(x2),r+) 4-5 4 Graphics 1 0.8 0.6 0.4 0.2 0 −0.2 −0.4 −0.6 −0.8 −1 0 1 2 3 4 5 6 7 For More Information See the "Basic Plotting" chapter of Using MATLAB Graphics for more examples of plotting options. Access Using MATLAB Graphics from the Help Desk. Imaginary and Complex Data When the arguments to plot are complex, the imaginary part is ignored except when plot is given a single complex argument. For this special case, the command is a shortcut for a plot of the real part versus the imaginary part. Therefore, plot(Z) where Z is a complex vector or matrix, is equivalent to plot(real(Z),imag(Z))4-6 Basic PlottingFor example, t = 0:pi/10:2*pi; plot(exp(i*t),-o) axis equaldraws a 20-sided polygon with little circles at the vertices. The command,axis equal, makes the individual tick mark increments on the x- and y-axesthe same length, which makes this plot more circular in appearance. 1 0.8 0.6 0.4 0.2 0 −0.2 −0.4 −0.6 −0.8 −1 −1 −0.5 0 0.5 1Adding Plots to an Existing GraphThe hold command enables you to add plots to an existing graph. When youtype hold onMATLAB does not replace the existing graph when you issue another plottingcommand; it adds the new data to the current graph, rescaling the axes ifnecessary. 4-7 4 Graphics For example, these statements first create a contour plot of the peaks function, then superimpose a pseudocolor plot of the same function. [x,y,z] = peaks; contour(x,y,z,20,k) hold on pcolor(x,y,z) shading interp hold off The hold on command causes the pcolor plot to be combined with the contour plot in one figure. For More Information See the "Specialized Graphs" chapter in Using MATLAB Graphics for information on a variety of graph types. Access Using MATLAB Graphics from the Help Desk.4-8 Basic PlottingFigure WindowsGraphing functions automatically open a new figure window if there are nofigure windows already on the screen. If a figure window exists, MATLAB usesthat window for graphics output. If there are multiple figure windows open,MATLAB targets the one that is designated the "current figure" (the last figureused or clicked in).To make an existing figure window the current figure, you can click the mousewhile the pointer is in that window or you can type figure(n)where n is the number in the figure title bar. The results of subsequentgraphics commands are displayed in this window.To open a new figure window and make it the current figure, type figureFor More Information See the "Figure Properties" chapter in UsingMATLAB Graphics and the reference page for the figure command. AccessUsing MATLAB Graphics and the figure reference page from the Help Desk.Multiple Plots in One FigureThe subplot command enables you to display multiple plots in the samewindow or print them on the same piece of paper. Typing subplot(m,n,p)partitions the figure window into an m-by-n matrix of small subplots and selectsthe pth subplot for the current plot. The plots are numbered along first the top 4-9 Basic PlottingControlling the AxesThe axis command supports a number of options for setting the scaling,orientation, and aspect ratio of plots.Setting Axis LimitsBy default, MATLAB finds the maxima and minima of the data to choose theaxis limits to span this range. The axis command enables you to specify yourown limits axis([xmin xmax ymin ymax])or for three-dimensional graphs, axis([xmin xmax ymin ymax zmin zmax])Use the command axis autoto re-enable MATLAB's automatic limit selection.Setting Axis Aspect Ratioaxis also enables you to specify a number of predefined modes. For example, axis squaremakes the x-axes and y-axes the same length. axis equalmakes the individual tick mark increments on the x- and y-axes the samelength. This means plot(exp(i*[0:pi/10:2*pi]))followed by either axis square or axis equal turns the oval into a propercircle. axis auto normalreturns the axis scaling to its default, automatic mode. 4-11 4 Graphics Setting Axis Visibility You can use the axis command to make the axis visible or invisible. axis on makes the axis visible. This is the default. axis off makes the axis invisible. Setting Grid Lines The grid command toggles grid lines on and off. The statement grid on turns the grid lines on and grid off turns them back off again. For More Information See the axis and axes reference pages and the "Axes Properties" chapter in Using MATLAB Graphics. Access these reference pages and Using MATLAB Graphics from the Help Desk. Axis Labels and Titles The xlabel, ylabel, and zlabel commands add x-, y-, and z-axis labels. The title command adds a title at the top of the figure and the text function inserts text anywhere in the figure. A subset of TeX notation produces Greek letters. t = -pi:pi/100:pi; y = sin(t); plot(t,y) axis([-pi pi -1 1]) xlabel(-pi leq {itt} leq pi) ylabel(sin(t)) title(Graph of the sine function) text(1,-1/3,{itNote the odd symmetry.})4-12 Basic Plotting Graph of the sine function 1 0.8 0.6 0.4 0.2 sin(t) 0 −0.2 Note the odd symmetry. −0.4 −0.6 −0.8 −1 −3 −2 −1 0 1 2 3 −π ≤ t ≤ πFor More Information See the "Labeling Graphs" chapter in UsingMATLAB Graphics for more information. Access Using MATLAB Graphicsfrom the Help Desk.Annotating Plots Using the Plot EditorAfter creating a plot, you can make changes to it and annotate it with the PlotEditor, which is an easy-to-use graphical interface. The following illustration 4-13 4 Graphics shows the plot in a figure window and labels the main features of the figure window and the Plot Editor. Use the Tools Click this button to Get help for Annotate Zoom and rotate the Menu to access Plot start Plot Editor the Plot the plot plot Editor features mode Editor To save a figure, select Save from the File menu. To save it using a graphics format, such as TIFF, for use with other applications, select Export from the File menu. You can also save from the command line – use the saveas command, including any options to save the figure in a different format.4-14 Mesh and Surface PlotsMesh and Surface Plots MATLAB defines a surface by the z-coordinates of points above a grid in the x-y plane, using straight lines to connect adjacent points. The mesh and surf plotting functions display surfaces in three dimensions. mesh produces wireframe surfaces that color only the lines connecting the defining points. surf displays both the connecting lines and the faces of the surface in color. Visualizing Functions of Two Variables To display a function of two variables, z = f (x,y): • Generate X and Y matrices consisting of repeated rows and columns, respectively, over the domain of the function. • Use X and Y to evaluate and graph the function. The meshgrid function transforms the domain specified by a single vector or two vectors x and y into matrices X and Y for use in evaluating functions of two variables. The rows of X are copies of the vector x and the columns of Y are copies of the vector y. Example – Graphing the sinc Function This example evaluates and graphs the two-dimensional sinc function, sin(r)/r, between the x and y directions. R is the distance from origin, which is at the center of the matrix. Adding eps (a MATLAB command that returns the smallest floating-point number on your system) avoids the indeterminate 0/0 at the origin. [X,Y] = meshgrid(-8:.5:8); R = sqrt(X.^2 + Y.^2) + eps; Z = sin(R)./R; mesh(X,Y,Z,EdgeColor,black) 4-15 4 Graphics 1 0.5 0 −0.5 10 5 10 0 5 0 −5 −5 −10 −10 By default, MATLAB colors the mesh using the current colormap. However, this example uses a single-colored mesh by specifying the EdgeColor surface property. See the surface reference page for a list of all surface properties. You can create a transparent mesh by disabling hidden line removal. hidden off See the hidden reference page for more information on this option. Example – Colored Surface Plots A surface plot is similar to a mesh plot except the rectangular faces of the surface are colored. The color of the faces is determined by the values of Z and the colormap (a colormap is an ordered list of colors). These statements graph the sinc function as a surface plot, select a colormap, and add a color bar to show the mapping of data to color. surf(X,Y,Z) colormap hsv colorbar4-16 Mesh and Surface Plots 1 1 0.8 0.6 0.5 0.4 0 0.2−0.5 10 0 5 10 0 5 0 −5 −0.2 −5 −10 −10See the colormap reference page for information on colormaps.For More Information See the "Creating 3-D Graphs" chapter in UsingMATLAB Graphics for more information on surface plots. Access UsingMATLAB Graphics from the Help Desk.Surface Plots with LightingLighting is the technique of illuminating an object with a directional lightsource. In certain cases, this technique can make subtle differences in surfaceshape easier to see. Lighting can also be used to add realism tothree-dimensional graphs.This example uses the same surface as the previous examples, but colors it redand removes the mesh lines. A light object is then added to the left of the"camera" (that is the location in space from where you are viewing the surface). 4-17 4 Graphics After adding the light and setting the lighting method to phong, use the view command to change the view point so you are looking at the surface from a different point in space (an azimuth of -15 and an elevation of 65 degrees). Finally, zoom in on the surface using the toolbar zoom mode. surf(X,Y,Z,FaceColor,red,EdgeColor,none); camlight left; lighting phong view(-15,65) For More Information See the "Lighting as a Visualization Tool" and "Defining the View" chapters in Using MATLAB Graphics for information on these techniques. Access Using MATLAB Graphics from the Help Desk.4-18 ImagesImages Two-dimensional arrays can be displayed as images, where the array elements determine brightness or color of the images. For example, the statements load durer whos Name Size Bytes Class X 648x509 2638656 double array caption 2x28 112 char array map 128x3 3072 double array load the file durer.mat, adding three variables to the workspace. The matrix X is a 648-by-509 matrix and map is a 128-by-3 matrix that is the colormap for this image. Note MAT-files, such as durer.mat, are binary files that can be created on one platform and later read by MATLAB on a different platform. The elements of X are integers between 1 and 128, which serve as indices into the colormap, map. Then image(X) colormap(map) axis image reproduces Dürer's etching shown at the beginning of this book. A high resolution scan of the magic square in the upper right corner is available in another file. Type load detail and then use the uparrow key on your keyboard to reexecute the image, colormap, and axis commands. The statement colormap(hot) adds some twentieth century colorization to the sixteenth century etching. The function hot generates a colormap containing shades of reds, oranges, and 4-19 4 Graphics yellows. Typically a given image matrix has a specific colormap associated with it. See the colormap reference page for a list of other predefined colormaps. For More Information See the "Displaying Bit-Mapped Images" chapter in Using MATLAB Graphics for information the image processing capabilities of MATLAB. Access Using MATLAB Graphics from the Help Desk.4-20 Printing GraphicsPrinting Graphics You can print a MATLAB figure directly on a printer connected to your computer or you can export the figure to one of the standard graphic file formats supported by MATLAB. There are two ways to print and export figures: • Using the Print option under the File menu • Using the print command Printing from the Menu There are four menu options under the File menu that pertain to printing: • The Page Setup option displays a dialog box that enables you to adjust characteristics of the figure on the printed page. • The Print Setup option displays a dialog box that sets printing defaults, but does not actually print the figure. • The Print Preview option enables you to view the figure the way it will look on the printed page. • The Print option displays a dialog box that lets you select standard printing options and print the figure. Generally, use Print Preview to determine whether the printed output is what you want. If not, use the Page Setup dialog box to change the output settings. The Page Setup dialog box Help button displays information on how to set up the page. Exporting Figure to Graphics Files The Export option under the File menu enables you to export the figure to a variety of standard graphics file formats. Using the Print Command The print command provides more flexibility in the type of output sent to the printer and allows you to control printing from M-files. The result can be sent directly to your default printer or stored in a specified file. A wide variety of output formats, including TIFF, JPEG, and PostScript, is available. For example, this statement saves the contents of the current figure window as color Encapsulated Level 2 PostScript in the file called magicsquare.eps. It 4-21 4 Graphics also includes a TIFF preview, which enables most word processors to display the picture print -depsc2 -tiff magicsquare.eps To save the same figure as a TIFF file with a resolution of 200 dpi, use the command print -dtiff -r200 magicsquare.tiff If you type print on the command line, print MATLAB prints the current figure on your default printer. For More Information See the print command reference page and the "Printing MATLAB Graphics" chapter in Using MATLAB Graphics for more information on printing. Access this information from the Help Desk.4-22 Handle GraphicsHandle Graphics When you use a plotting command, MATLAB creates the graph using various graphics objects, such as lines, text, and surfaces (see Table 4-1 for a complete list). All graphics objects have properties that control the appearance and behavior of the object. MATLAB enables you to query the value of each property and set the value of most properties. Whenever MATLAB creates a graphics object, it assigns an identifier (called a handle) to the object. You can use this handle to access the object's properties. Handle Graphics is useful if you want to: • Modify the appearance of graphs. • Create custom plotting commands by writing M-files that create and manipulate objects directly. The material in this manual concentrates on modifying the appearance of graphs. See the "Handle Graphics" chapter in Using MATLAB Graphics for more information on programming with Handle Graphics. Graphics Objects Graphics objects are the basic elements used to display graphics and user interface elements. Table 4-1 lists the graphics objects. Table 4-1: Handle Graphics Objects Object Description Root Top of the hierarchy corresponding to the computer screen Figure Window used to display graphics and user interfaces Uicontrol User interface control that executes a function in response to user interaction Uimenu User-defined figure window menu Uicontextmenu Pop-up menu invoked by right clicking on a graphics object 4-23 4 Graphics Table 4-1: Handle Graphics Objects (Continued) Object Description Axes Axes for displaying graphs in a figure Image Two-dimensional pixel-based picture Light Light sources that affect the coloring of patch and surface objects Line Line used by functions such as plot, plot3, semilogx Patch Filled polygon with edges Rectangle Two-dimensional shape varying from rectangles to ovals Surface Three-dimensional representation of matrix data created by plotting the value of the data as heights above the x-y plane Text Character string Object Hierarchy The objects are organized in a tree structured hierarchy reflecting their interdependence. For example, line objects require axes objects as a frame of reference. In turn, axes objects exist only within figure objects. This diagram illustrates the tree structure. Root Figure Axes Uicontrol Uimenu Uicontextmenu Image Light Line Patch Rectangle Surface Text4-24 Handle GraphicsCreating ObjectsEach object has an associated function that creates the object. These functionshave the same name as the objects they create. For example, the text functioncreates text objects, the figure function creates figure objects, and so on.MATLAB's high-level graphics functions (like plot and surf) call theappropriate low-level function to draw their respective graphics.For More Information See the object creation function reference page formore information about the object and a description of the object's properties.Commands for Working with ObjectsThis table lists commands commonly used when working with objects. Function Purpose copyobj Copy graphics object delete Delete an object findobj Find the handle of objects having specified property values gca Return the handle of the current axes gcf Return the handle of the current figure gco Return the handle of the current object get Query the value of an objects properties set Set the value of an objects propertiesFor More Information See MATLAB Functions in the Help Desk for adescription of each of these functions. 4-25 4 Graphics Setting Object Properties All object properties have default values. However, you may find it useful to change the settings of some properties to customize your graph. There are two ways to set object properties: • Specify values for properties when you create the object. • Set the property value on an object that already exists. You can specify object property values as arguments to object creation functions as well as with plotting function, such as plot, mesh, and surf. You can use the set command to modify the property values of existing objects. For More Information See Handle Graphics Properties in the Help Desk for a description of all object properties. Setting Properties from Plotting Commands Plotting commands that create lines or surfaces enable you to specify property name/property value pairs as arguments. For example, the command plot(x,y,LineWidth,1.5) plots the data in the variables x and y using lines having a LineWidth property set to 1.5 points (one point = 1/72 inch). You can set any line object property this way. Setting Properties of Existing Objects Many plotting commands can also return the handles of the objects created so you can modify the objects using the set command. For example, these statements plot a five-by-five matrix (creating five lines, one per column) and then set the Marker to a square and the MarkerFaceColor to green. h = plot(magic(5)); set(h,Marker,s,MarkerFaceColor,g) In this case, h is a vector containing five handles, one for each of the five lines in the plot. The set statement sets the Marker and MarkerFaceColor properties of all lines to the same values.4-26 Handle GraphicsSetting Multiple Property ValuesIf you want to set the properties of each line to a different value, you can usecell arrays to store all the data and pass it to the set command. For example,create a plot and save the line handles. h = plot(magic(5));Suppose you want to add different markers to each line and color the marker'sface color to the same color as the line. You need to define two cell arrays – onecontaining the property names and the other containing the desired values ofthe properties.The prop_name cell array contains two elements. prop_name(1) = {Marker}; prop_name(2) = {MarkerFaceColor};The prop_values cell array contains 10 values – five values for the Markerproperty and five values for the MarkerFaceColor property. Notice thatprop_values is a two-dimensional cell array. The first dimension indicateswhich handle in h the values apply to and the second dimension indicateswhich property the value is assigned to. prop_values(1,1) = {s}; prop_values(1,2) = {get(h(1),Color)}; prop_values(2,1) = {d}; prop_values(2,2) = {get(h(2),Color)}; prop_values(3,1) = {o}; prop_values(3,2) = {get(h(3),Color)}; prop_values(4,1) = {p}; prop_values(4,2) = {get(h(4),Color)}; prop_values(5,1) = {h}; prop_values(5,2) = {get(h(5),Color)};The MarkerFaceColor is always assigned the value of the corresponding line'scolor (obtained by getting the line's Color property with the get command).After defining the cell arrays, call set to specify the new property values. set(h,prop_name,prop_values) 4-27 4 Graphics 25 20 15 10 5 0 1 1.5 2 2.5 3 3.5 4 4.5 5 For More Information See the "Structures and Cell Arrays" chapter in Using MATLAB for information on cell arrays. Access Using MATLAB from the Help Desk. Finding the Handles of Existing Objects The findobj command enables you to obtain the handles of graphics objects by searching for objects with particular property values. With findobj you can specify the value of any combination of properties, which makes it easy to pick one object out of many. For example, you may want to find the blue line with square marker having blue face color. You can also specify which figures or axes to search, if there is more than one. The following sections provide examples illustrating how to use findobj.4-28 Handle GraphicsFinding All Objects of a Certain TypeSince all objects have a Type property that identifies the type of object, you canfind the handles of all occurrences of a particular type of object. For example, h = findobj(Type,line);finds the handles of all line objects.Finding Objects with a Particular PropertyYou can specify multiple properties to narrow the search. For example, h = findobj(Type,line,Color,r,LineStyle,:);finds the handles of all red, dotted lines.Limiting the Scope of the SearchYou can specify the starting point in the object hierarchy by passing the handleof the starting figure or axes as the first argument. For example, h = findobj(gca,Type,text,String,pi/2);finds the string π/2 only within the current axes.Using findobj as an ArgumentSince findobj returns the handles it finds, you can use it in place of the handleargument. For example, set(findobj(Type,line,Color,red),LineStyle,:)finds all red lines and sets their line style to dotted.For More Information See the "Accessing Object Handles" section of theHandle Graphics chapter in Using MATLAB Graphics for more information.Access Using MATLAB Graphics from the Help Desk. 4-29 4 Graphics Graphics User Interfaces Here is a simple example illustrating how to use Handle Graphics to build user interfaces. The statement b = uicontrol(Style,pushbutton, ... Units,normalized, ... Position,[.5 .5 .2 .1], ... String,click here); creates a pushbutton in the center of a figure window and returns a handle to the new object. But, so far, clicking on the button does nothing. The statement s = set(b,Position,[.8*rand .9*rand .2 .1]); creates a string containing a command that alters the pushbutton's position. Repeated execution of eval(s) moves the button to random positions. Finally, set(b,Callback,s) installs s as the button's callback action, so every time you click on the button, it moves to a new position. Graphical User Interface Design Tools MATLAB provides GUI Design Environment (GUIDE) tools that simplify the creation of graphical user interfaces. To display the GUIDE control panel, issue the guide command. For More Information Type help guide at the MATLAB command line.4-30 AnimationsAnimations MATLAB provides two ways of generating moving, animated graphics: • Continually erase and then redraw the objects on the screen, making incremental changes with each redraw. • Save a number of different pictures and then play them back as a movie. Erase Mode Method Using the EraseMode property is appropriate for long sequences of simple plots where the change from frame to frame is minimal. Here is an example showing simulated Brownian motion. Specify a number of points, such as n = 20 and a temperature or velocity, such as s = .02 The best values for these two parameters depend upon the speed of your particular computer. Generate n random points with (x,y) coordinates between -1/2 and +1/2. x = rand(n,1)-0.5; y = rand(n,1)-0.5; Plot the points in a square with sides at -1 and +1. Save the handle for the vector of points and set its EraseMode to xor. This tells the MATLAB graphics system not to redraw the entire plot when the coordinates of one point are changed, but to restore the background color in the vicinity of the point using an "exclusive or" operation. h = plot(x,y,.); axis([-1 1 -1 1]) axis square grid off set(h,EraseMode,xor,MarkerSize,18) Now begin the animation. Here is an infinite while loop, which you can eventually exit by typing Ctrl-c. Each time through the loop, add a small amount of normally distributed random noise to the coordinates of the points. 4-31 4 Graphics Then, instead of creating an entirely new plot, simply change the XData and YData properties of the original plot. while 1 drawnow x = x + s*randn(n,1); y = y + s*randn(n,1); set(h,XData,x,YData,y) end How long does it take for one of the points to get outside of the square? How long before all of the points are outside the square? 1 0.8 0.6 0.4 0.2 0 −0.2 −0.4 −0.6 −0.8 −1 −1 −0.5 0 0.5 1 Creating Movies If you increase the number of points in the Brownian motion example to something like n = 300 and s = .02, the motion is no longer very fluid; it takes too much time to draw each time step. It becomes more effective to save a predetermined number of frames as bitmaps and to play them back as a movie.4-32 5 Programming with MATLAB Flow Control MATLAB has several flow control constructs: • if statements • switch statements • for loops • while loops • break statements For More Information Using MATLAB discusses programming in MATLAB. Access Using MATLAB from the Help Desk. if The if statement evaluates a logical expression and executes a group of statements when the expression is true. The optional elseif and else keywords provide for the execution of alternate groups of statements. An end keyword, which matches the if, terminates the last group of statements. The groups of statements are delineated by the four keywords – no braces or brackets are involved. MATLAB's algorithm for generating a magic square of order n involves three different cases: when n is odd, when n is even but not divisible by 4, or when n is divisible by 4. This is described by if rem(n,2) ~= 0 M = odd_magic(n) elseif rem(n,4) ~= 0 M = single_even_magic(n) else M = double_even_magic(n) end In this example, the three cases are mutually exclusive, but if they weren't, the first true condition would be executed.5-2 Flow ControlIt is important to understand how relational operators and if statements workwith matrices. When you want to check for equality between two variables, youmight use if A == B, ...This is legal MATLAB code, and does what you expect when A and B are scalars.But when A and B are matrices, A == B does not test if they are equal, it testswhere they are equal; the result is another matrix of 0's and 1's showingelement-by-element equality. In fact, if A and B are not the same size, thenA == B is an error.The proper way to check for equality between two variables is to use theisequal function, if isequal(A,B), ...Here is another example to emphasize this point. If A and B are scalars, thefollowing program will never reach the unexpected situation. But for mostpairs of matrices, including our magic squares with interchanged columns,none of the matrix conditions A > B, A < B or A == B is true for all elementsand so the else clause is executed. if A > B greater elseif A < B less elseif A == B equal else error(Unexpected situation) endSeveral functions are helpful for reducing the results of matrix comparisons toscalar conditions for use with if, including isequal isempty all any 5-3 5 Programming with MATLAB switch and case The switch statement executes groups of statements based on the value of a variable or expression. The keywords case and otherwise delineate the groups. Only the first matching case is executed. There must always be an end to match the switch. The logic of the magic squares algorithm can also be described by switch (rem(n,4)==0) + (rem(n,2)==0) case 0 M = odd_magic(n) case 1 M = single_even_magic(n) case 2 M = double_even_magic(n) otherwise error(This is impossible) end Note for C Programmers Unlike the C language switch statement, MATLAB's switch does not fall through. If the first case statement is true, the other case statements do not execute. So, break statements are not required. for The for loop repeats a group of statements a fixed, predetermined number of times. A matching end delineates the statements. for n = 3:32 r(n) = rank(magic(n)); end r The semicolon terminating the inner statement suppresses repeated printing, and the r after the loop displays the final result.5-4 Flow ControlIt is a good idea to indent the loops for readability, especially when they arenested. for i = 1:m for j = 1:n H(i,j) = 1/(i+j); end endwhileThe while loop repeats a group of statements an indefinite number of timesunder control of a logical condition. A matching end delineates the statements.Here is a complete program, illustrating while, if, else, and end, that usesinterval bisection to find a zero of a polynomial. a = 0; fa = -Inf; b = 3; fb = Inf; while b-a > eps*b x = (a+b)/2; fx = x^3-2*x-5; if sign(fx) == sign(fa) a = x; fa = fx; else b = x; fb = fx; end end xThe result is a root of the polynomial x3 - 2x - 5, namely x = 2.09455148154233The cautions involving matrix comparisons that are discussed in the section onthe if statement also apply to the while statement.breakThe break statement lets you exit early from a for or while loop. In nestedloops, break exits from the innermost loop only. 5-5 Other Data StructuresOther Data Structures This section introduces you to some other data structures in MATLAB, including: • Multidimensional arrays • Cell arrays • Characters and text • Structures For More Information For a complete discussion of MATLAB's data structures, see Using MATLAB, which is accessible from the Help Desk. Multidimensional Arrays Multidimensional arrays in MATLAB are arrays with more than two subscripts. They can be created by calling zeros, ones, rand, or randn with more than two arguments. For example, R = randn(3,4,5); creates a 3-by-4-by-5 array with a total of 3x4x5 = 60 normally distributed random elements. A three-dimensional array might represent three-dimensional physical data, say the temperature in a room, sampled on a rectangular grid. Or, it might represent a sequence of matrices, A(k), or samples of a time-dependent matrix, A(t). In these latter cases, the (i, j)th element of the kth matrix, or the tkth matrix, is denoted by A(i,j,k). MATLAB's and Dürer's versions of the magic square of order 4 differ by an interchange of two columns. Many different magic squares can be generated by interchanging columns. The statement p = perms(1:4); 5-7 5 Programming with MATLAB produces a 1-by-3 cell array. The three cells contain the magic square, the row vector of column sums, and the product of all its elements. When C is displayed, you see C = [4x4 double] [1x4 double] [20922789888000] This is because the first two cells are too large to print in this limited space, but the third cell contains only a single number, 16!, so there is room to print it. Here are two important points to remember. First, to retrieve the contents of one of the cells, use subscripts in curly braces. For example, C{1} retrieves the magic square and C{3} is 16!. Second, cell arrays contain copies of other arrays, not pointers to those arrays. If you subsequently change A, nothing happens to C. Three-dimensional arrays can be used to store a sequence of matrices of the same size. Cell arrays can be used to store a sequence of matrices of different sizes. For example, M = cell(8,1); for n = 1:8 M{n} = magic(n); end M produces a sequence of magic squares of different order, M = [ 1] [ 2x2 double] [ 3x3 double] [ 4x4 double] [ 5x5 double] [ 6x6 double] [ 7x7 double] [ 8x8 double]5-10 5 Programming with MATLAB Internally, the characters are stored as numbers, but not in floating-point format. The statement a = double(s) converts the character array to a numeric matrix containing floating-point representations of the ASCII codes for each character. The result is a = 72 101 108 108 111 The statement s = char(a) reverses the conversion. Converting numbers to characters makes it possible to investigate the various fonts available on your computer. The printable characters in the basic ASCII character set are represented by the integers 32:127. (The integers less than 32 represent nonprintable control characters.) These integers are arranged in an appropriate 6-by-16 array with F = reshape(32:127,16,6); The printable characters in the extended ASCII character set are represented by F+128. When these integers are interpreted as characters, the result depends on the font currently being used. Type the statements char(F) char(F+128) and then vary the font being used for the MATLAB command window. On a PC, select Preferences under the File menu. Be sure to try the Symbol and5-12 5 Programming with MATLAB same length, and forms a character array with each line in a separate row. For example, S = char(A,rolling,stone,gathers,momentum.) produces a 5-by-9 character array S = A rolling stone gathers momentum. There are enough blanks in each of the first four rows of S to make all the rows the same length. Alternatively, you can store the text in a cell array. For example, C = {A;rolling;stone;gathers;momentum.} is a 5-by-1 cell array C = A rolling stone gathers momentum. You can convert a padded character array to a cell array of strings with C = cellstr(S) and reverse the process with S = char(C) Structures Structures are multidimensional MATLAB arrays with elements accessed by textual field designators. For example, S.name = Ed Plum; S.score = 83; S.grade = B+5-14 Other Data Structurescreates a scalar structure with three fields. S = name: Ed Plum score: 83 grade: B+Like everything else in MATLAB, structures are arrays, so you can insertadditional elements. In this case, each element of the array is a structure withseveral fields. The fields can be added one at a time, S(2).name = Toni Miller; S(2).score = 91; S(2).grade = A-;or, an entire element can be added with a single statement. S(3) = struct(name,Jerry Garcia,... score,70,grade,C)Now the structure is large enough that only a summary is printed. S = 1x3 struct array with fields: name score gradeThere are several ways to reassemble the various fields into other MATLABarrays. They are all based on the notation of a comma separated list. If you type S.scoreit is the same as typing S(1).score, S(2).score, S(3).scoreThis is a comma separated list. Without any other punctuation, it is not veryuseful. It assigns the three scores, one at a time, to the default variable ans anddutifully prints out the result of each assignment. But when you enclose theexpression in square brackets, [S.score] 5-15 5 Programming with MATLAB it is the same as [S(1).score, S(2).score, S(3).score] which produces a numeric row vector containing all of the scores. ans = 83 91 70 Similarly, typing S.name just assigns the names, one at time, to ans. But enclosing the expression in curly braces, {S.name} creates a 1-by-3 cell array containing the three names. ans = Ed Plum Toni Miller Jerry Garcia And char(S.name) calls the char function with three arguments to create a character array from the name fields, ans = Ed Plum Toni Miller Jerry Garcia5-16 Scripts and FunctionsScripts and Functions MATLAB is a powerful programming language as well as an interactive computational environment. Files that contain code in the MATLAB language are called M-files. You create M-files using a text editor, then use them as you would any other MATLAB function or command. There are two kinds of M-files: • Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace. • Functions, which can accept input arguments and return output arguments. Internal variables are local to the function. If you're a new MATLAB programmer, just create the M-files that you want to try out in the current directory. As you develop more of your own M-files, you will want to organize them into other directories and personal toolboxes that you can add to MATLAB's search path. If you duplicate function names, MATLAB executes the one that occurs first in the search path. To view the contents of an M-file, for example, myfunction.m, use type myfunction Scripts When you invoke a script, MATLAB simply executes the commands found in the file. Scripts can operate on existing data in the workspace, or they can create new data on which to operate. Although scripts do not return output arguments, any variables that they create remain in the workspace, to be used in subsequent computations. In addition, scripts can produce graphical output using functions like plot. 5-17 5 Programming with MATLAB For example, create a file called magicrank.m that contains these MATLAB commands. % Investigate the rank of magic squares r = zeros(1,32); for n = 3:32 r(n) = rank(magic(n)); end r bar(r) Typing the statement magicrank causes MATLAB to execute the commands, compute the rank of the first 30 magic squares, and plot a bar graph of the result. After execution of the file is complete, the variables n and r remain in the workspace. 35 30 25 20 15 10 5 0 0 5 10 15 20 25 30 355-18 Scripts and FunctionsFunctionsFunctions are M-files that can accept input arguments and return outputarguments. The name of the M-file and of the function should be the same.Functions operate on variables within their own workspace, separate from theworkspace you access at the MATLAB command prompt.A good example is provided by rank. The M-file rank.m is available in thedirectory toolbox/matlab/matfunYou can see the file with type rankHere is the file. function r = rank(A,tol) % RANK Matrix rank. % RANK(A) provides an estimate of the number of linearly % independent rows or columns of a matrix A. % RANK(A,tol) is the number of singular values of A % that are larger than tol. % RANK(A) uses the default tol = max(size(A)) * norm(A) * eps. s = svd(A); if nargin==1 tol = max(size(A)) * max(s) * eps; end r = sum(s > tol);The first line of a function M-file starts with the keyword function. It gives thefunction name and order of arguments. In this case, there are up to two inputarguments and one output argument.The next several lines, up to the first blank or executable line, are commentlines that provide the help text. These lines are printed when you type help rankThe first line of the help text is the H1 line, which MATLAB displays when youuse the lookfor command or request help on a directory. 5-19 5 Programming with MATLAB The rest of the file is the executable MATLAB code defining the function. The variable s introduced in the body of the function, as well as the variables on the first line, r, A and tol, are all local to the function; they are separate from any variables in the MATLAB workspace. This example illustrates one aspect of MATLAB functions that is not ordinarily found in other programming languages – a variable number of arguments. The rank function can be used in several different ways. rank(A) r = rank(A) r = rank(A,1.e-6) Many M-files work this way. If no output argument is supplied, the result is stored in ans. If the second input argument is not supplied, the function computes a default value. Within the body of the function, two quantities named nargin and nargout are available which tell you the number of input and output arguments involved in each particular use of the function. The rank function uses nargin, but does not need to use nargout. Global Variables If you want more than one function to share a single copy of a variable, simply declare the variable as global in all the functions. Do the same thing at the command line if you want the base workspace to access the variable. The global declaration must occur before the variable is actually used in a function. Although it is not required, using capital letters for the names of global variables helps distinguish them from other variables. For example, create an M-file called falling.m. function h = falling(t) global GRAVITY h = 1/2*GRAVITY*t.^2; Then interactively enter the statements global GRAVITY GRAVITY = 32; y = falling((0:.1:5)); The two global statements make the value assigned to GRAVITY at the command prompt available inside the function. You can then modify GRAVITY interactively and obtain new solutions without editing any files.5-20 Scripts and FunctionsPassing String Arguments to FunctionsYou can write MATLAB functions that accept string arguments without theparentheses and quotes. That is, MATLAB interprets foo a b cas foo(a,b,c)However, when using the unquoted form, MATLAB cannot return outputarguments. For example, legend apples orangescreates a legend on a plot using the strings apples and oranges as labels. If youwant the legend command to return its output arguments, then you must usethe quoted form. [legh,objh] = legend(apples,oranges);In addition, you cannot use the unquoted form if any of the arguments are notstrings.Building Strings on the FlyThe quoted form enables you to construct string arguments within the code.The following example processes multiple data files, August1.dat,August2.dat, and so on. It uses the function int2str, which converts aninteger to a character, to build the filename. for d = 1:31 s = [August int2str(d) .dat]; load(s) % Code to process the contents of the d-th file end 5-21 5 Programming with MATLAB A Cautionary Note While the unquoted syntax is convenient, it can be used incorrectly without causing MATLAB to generate an error. For example, given a matrix A, A = 0 -6 -1 6 2 -16 -5 20 -10 The eig command returns the eigenvalues of A. eig(A) ans = -3.0710 -2.4645+17.6008i -2.4645-17.6008i The following statement is not allowed because A is not a string, however MATLAB does not generate an error. eig A ans = 65 MATLAB actually takes the eigenvalues of ASCII numeric equivalent of the letter A (which is the number 65). The eval Function The eval function works with text variables to implement a powerful text macro facility. The expression or statement eval(s) uses the MATLAB interpreter to evaluate the expression or execute the statement contained in the text string s.5-22 Scripts and Functions The example of the previous section could also be done with the following code, although this would be somewhat less efficient because it involves the full interpreter, not just a function call. for d = 1:31 s = [load August int2str(d) .dat]; eval(s) % Process the contents of the d-th file end Vectorization To obtain the most speed out of MATLAB, it's important to vectorize the algorithms in your M-files. Where other programming languages might use for or DO loops, MATLAB can use vector or matrix operations. A simple example involves creating a table of logarithms. x = 0; for k = 1:1001 y(k) = log10(x); x = x + .01; endExperienced MATLAB users A vectorized version of the same code islike to say "Life is too short x = 0:.01:10;to spend writing for loops." y = log10(x); For more complicated code, vectorization options are not always so obvious. When speed is important, however, you should always look for ways to vectorize your algorithms. Preallocation If you can't vectorize a piece of code, you can make your for loops go faster by preallocating any vectors or arrays in which output results are stored. For example, this code uses the function zeros to preallocate the vector created in the for loop. This makes the for loop execute significantly faster. r = zeros(32,1); for n = 1:32 r(n) = rank(magic(n)); end 5-23 5 Programming with MATLAB Without the preallocation in the previous example, the MATLAB interpreter enlarges the r vector by one element each time through the loop. Vector preallocation eliminates this step and results in faster execution. Function Functions A class of functions, called "function functions," works with nonlinear functions of a scalar variable. That is, one function works on another function. The function functions include: • Zero finding • Optimization • Quadrature • Ordinary differential equations MATLAB represents the nonlinear function by a function M-file. For example, here is a simplified version of the function humps from the matlab/demos directory. function y = humps(x) y = 1./((x-.3).^2 + .01) + 1./((x-.9).^2 + .04) - 6; Evaluate this function at a set of points in the interval 0 ≤ x ≤ 1 with x = 0:.002:1; y = humps(x); Then plot the function with plot(x,y)5-24 Scripts and Functions 100 90 80 70 60 50 40 30 20 10 0 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1The graph shows that the function has a local minimum near x = 0.6. Thefunction fmins finds the minimizer, the value of x where the function takes onthis minimum. The first argument to fmins is the name of the function beingminimized and the second argument is a rough guess at the location of theminimum. p = fmins(humps,.5) p = 0.6370To evaluate the function at the minimizer, humps(p) ans = 11.2528Numerical analysts use the terms quadrature and integration to distinguishbetween numerical approximation of definite integrals and numerical 5-25 5 Programming with MATLAB integration of ordinary differential equations. MATLAB's quadrature routines are quad and quad8. The statement Q = quad8(humps,0,1) computes the area under the curve in the graph and produces Q = 29.8583 Finally, the graph shows that the function is never zero on this interval. So, if you search for a zero with z = fzero(humps,.5) you will find one outside of the interval z = -0.13165-26 Demonstration Programs Included with MATLABDemonstration Programs Included with MATLAB This section includes information on many of the demonstration programs that are included with MATLAB. For More Information The MathWorks Web site ( contains numerous M-files that have been written by users and MathWorks staff. These are accessible by selecting Download M-Files. Also, Technical Notes, which is accessible from our Technical Support Web site ( contains numerous examples on graphics, mathematics, API, Simulink, and others. There are many programs included with MATLAB that highlight various features and functions. For a complete list of the demos, at the command prompt type help demos To view a specific file, for example, airfoil, type edit airfoil To run a demonstration, type the filename at the command prompt. For example, to run the airfoil demonstration, type airfoil Note Many of the demonstrations use multiple windows and require you to press a key in the MATLAB command window to continue through the demonstration. 5-27 6 Symbolic Math Toolbox Introduction The Symbolic Math Toolbox incorporates symbolic computation into MATLAB's numeric environment. This toolbox supplements MATLAB's numeric and graphical facilities with several other types of mathematical computation. Facility Covers Calculus Differentiation, integration, limits, summation, and Taylor series Linear Algebra Inverses, determinants, eigenvalues, singular value decomposition, and canonical forms of symbolic matrices Simplification Methods of simplifying algebraic expressions Solution of Symbolic and numerical solutions to algebraic and Equations differential equations Transforms Fourier, Laplace, z-transform, and corresponding inverse transforms Variable-Precision Numerical evaluation of mathematical expressions Arithmetic to any specified accuracy The computational engine underlying the toolboxes is the kernel of Maple, a system developed primarily at the University of Waterloo, Canada, and, more recently, at the Eidgenössiche Technische Hochschule, Zürich, Switzerland. Maple is marketed and supported by Waterloo Maple, Inc. This version of the Symbolic Math Toolbox is designed to work with MATLAB 5.3 and Maple V Release 5. The Symbolic Math Toolbox is a collection of more than one-hundred MATLAB functions that provide access to the Maple kernel using a syntax and style that is a natural extension of the MATLAB language. The toolbox also allows you to access functions in Maple's linear algebra package. With this toolbox, you can write your own M-files to access Maple functions and the Maple workspace.6-2 IntroductionThe following sections of this tutorial provide explanation and examples onhow to use the toolbox. Section Covers "Getting Help" How to get online help for Symbolic Math Toolbox functions "Getting Started" Basic symbolic math operations "Calculus" How to differentiate and integrate symbolic expressions "Simplifications and How to simplify and substitute values into Substitutions" expressions "Variable-Precision How to control the precision of Arithmetic" computations "Linear Algebra" Examples using the toolbox functions "Solving Equations" How to solve symbolic equationsFor More Information You can access complete reference information for theSymbolic Math Toolbox functions from the Help Desk. Also, you can print thePDF version of the Symbolic Math Toolbox User's Guide (tutorial andreference information) by selecting Symbolic Math Toolbox User's Guidefrom Online Manuals on the Help Desk. 6-3 6 Symbolic Math Toolbox Getting Help There are several ways to find information on using Symbolic Math Toolbox functions. One, of course, is to read this chapter! Another is to use the Help Desk, which contains reference information for all the functions. You can also use MATLAB's command line help system. Generally, you can obtain help on MATLAB functions simply by typing help function where function is the name of the MATLAB function for which you need help. This is not sufficient, however, for some Symbolic Math Toolbox functions. The reason? The Symbolic Math Toolbox "overloads" many of MATLAB's numeric functions. That is, it provides symbolic-specific implementations of the functions, using the same function name. To obtain help for the symbolic version of an overloaded function, type help sym/function where function is the overloaded function's name. For example, to obtain help on the symbolic version of the overloaded function, diff, type help sym/diff To obtain information on the numeric version, on the other hand, simply type help diff How can you tell whether a function is overloaded? The help for the numeric version tells you so. For example, the help for the diff function contains the section Overloaded methods help char/diff.m help sym/diff.m This tells you that there are two other diff commands that operate on expressions of class char and class sym, respectively. See the next section for information on class sym. For more information on overloaded commands, see the Using MATLAB guide, which is accessible from the Help Desk.6-4 Getting StartedGetting Started This section describes how to create and use symbolic objects. It also describes the default symbolic variable. If you are familiar with version 1 of the Symbolic Math Toolbox, please note that version 2 uses substantially different and simpler syntax. To get a quick online introduction to the Symbolic Math Toolbox, type demos at the MATLAB command line. MATLAB displays the MATLAB Demos dialog box. Select Symbolic Math (in the left list box) and then Introduction (in the right list box). Symbolic Objects The Symbolic Math Toolbox defines a new MATLAB data type called a symbolic object or sym (see Using MATLAB for an introduction to MATLAB classes and objects). Internally, a symbolic object is a data structure that stores a string representation of the symbol. The Symbolic Math Toolbox uses symbolic objects to represent symbolic variables, expressions, and matrices. 6-5 Getting Startedoperations (e.g., integration, differentiation, substitution, etc.) on f, you needto create the variables explicitly. You can do this by typing a = sym(a) b = sym(b) c = sym(c) x = sym(x)or simply syms a b c xIn general, you can use sym or syms to create symbolic variables. Werecommend you use syms because it requires less typing.Symbolic and Numeric ConversionsConsider the ordinary MATLAB quantity t = 0.1The sym function has four options for returning a symbolic representation ofthe numeric value stored in t. The f option sym(t,f)returns a symbolic floating-point representation 1.999999999999a*2^(-4)The r option sym(t,r)returns the rational form 1/10This is the default setting for sym. That is, calling sym without a secondargument is the same as using sym with the r option. sym(t) ans = 1/10 6-7 6 Symbolic Math Toolbox The third option e returns the rational form of t plus the difference between the theoretical rational expression for t and its actual (machine) floating-point value in terms of eps (the floating-point relative accuracy). sym(t,e) ans = 1/10+eps/40 The fourth option d returns the decimal expansion of t up to the number of significant digits specified by digits. sym(t,d) ans = .10000000000000000555111512312578 The default value of digits is 32 (hence, sym(t,d) returns a number with 32 significant digits), but if you prefer a shorter representation, use the digits command as follows. digits(7) sym(t,d) ans = .1000000 A particularly effective use of sym is to convert a matrix from numeric to symbolic form. The command A = hilb(3) generates the 3-by-3 Hilbert matrix. A = 1.0000 0.5000 0.3333 0.5000 0.3333 0.2500 0.3333 0.2500 0.2000 By applying sym to A A = sym(A)6-8 6 Symbolic Math Toolbox The command clear x does not make x a nonreal variable. Creating Abstract Functions If you want to create an abstract (i.e., indeterminant) function f(x), type f = sym(f(x)) Then f acts like f(x) and can be manipulated by the toolbox commands. To construct the first difference ratio, for example, type df = (subs(f,x,x+h) - f)/h or syms x h df = (subs(f,x,x+h)-f)/h which returns df = (f(x+h)-f(x))/h This application of sym is useful when computing Fourier, Laplace, and z-transforms. Example: Creating a Symbolic Matrix A circulant matrix has the property that each row is obtained from the previous one by cyclically permuting the entries one step forward. We create the circulant matrix A whose elements are a, b, and c, using the commands syms a b c A = [a b c; b c a; c a b] which return A = [ a, b, c ] [ b, c, a ] [ c, a, b ]6-10 Getting StartedSince A is circulant, the sum over each row and column is the same. Let's checkthis for the first row and second column. The command sum(A(1,:))returns ans = a+b+cThe command sum(A(1,:)) == sum(A(:,2)) % This is a logical test.returns ans = 1Now replace the (2,3) entry of A with beta and the variable b with alpha. Thecommands syms alpha beta; A(2,3) = beta; A = subs(A,b,alpha)return A = [ a, alpha, c] [ alpha, c, beta] [ c, a, alpha]From this example, you can see that using symbolic objects is very similar tousing regular MATLAB numeric objects. 6-11 6 Symbolic Math Toolbox The Default Symbolic Variable When manipulating mathematical functions, the choice of the independent variable is often clear from context. For example, consider the expressions in the table below. Mathematical Function MATLAB Command f = xn f = x^n g = sin(at+b) g = sin(a*t + b) h = Jν(z) h = besselj(nu,z) If we ask for the derivatives of these expressions, without specifying the independent variable, then by mathematical convention we obtain f = nxn, g = a cos(at + b), and h = Jv(z)(v/z) - Jv+1(z). Let's assume that the independent variables in these three expressions are x, t, and z, respectively. The other symbols, n, a, b, and v, are usually regarded as "constants" or "parameters." If, however, we wanted to differentiate the first expression with respect to n, for example, we could write d d n ------ ( x ) or ------ -f -x dn dn to get xn ln x. By mathematical convention, independent variables are often lower-case letters found near the end of the Latin alphabet (e.g., x, y, or z). This is the idea behind findsym, a utility function in the toolbox used to determine default symbolic variables. Default symbolic variables are utilized by the calculus, simplification, equation-solving, and transform functions. To apply this utility to the example discussed above, type syms a b n nu t x z f = x^n; g = sin(a*t + b); h = besselj(nu,z); This creates the symbolic expressions f, g, and h to match the example. To differentiate these expressions, we use diff. diff(f)6-12 Getting Startedreturns ans = x^n*n/xSee the section "Differentiation" for a more detailed discussion ofdifferentiation and the diff command.Here, as above, we did not specify the variable with respect to differentiation.How did the toolbox determine that we wanted to differentiate with respect tox? The answer is the findsym command findsym(f,1)which returns ans = xSimilarly, findsym(g,1) and findsym(h,1) return t and z, respectively. Herethe second argument of findsym denotes the number of symbolic variables wewant to find in the symbolic object f, using the findsym rule (see below). Theabsence of a second argument in findsym results in a list of all symbolicvariables in a given symbolic expression. We see this demonstrated below. Thecommand findsym(g)returns the result ans = a, b, tfindsym Rule The default symbolic variable in a symbolic expression is theletter that is closest to x alphabetically. If there are two equally close, theletter later in the alphabet is chosen. 6-13 Getting StartedCreating an M-FileM-files permit a more general use of functions. Suppose, for example, you wantto create the sinc function sin(x)/x. To do this, create an M-file in the @symdirectory. function z = sinc(x) %SINC The symbolic sinc function % sin(x)/x. This function % accepts a sym as the input argument. if isequal(x,sym(0)) z = 1; else z = sin(x)/x; endYou can extend such examples to functions of several variables. For a moredetailed discussion on object-oriented programming, see the Using MATLABguide. 6-15 6 Symbolic Math Toolbox Calculus The Symbolic Math Toolbox provides functions to do the basic operations of calculus; differentiation, limits, integration, summation, and Taylor series expansion. The following sections outline these functions. Differentiation Let's create a symbolic expression. syms a x f = sin(a*x) Then diff(f) differentiates f with respect to its symbolic variable (in this case x), as determined by findsym. ans = cos(a*x)*a To differentiate with respect to the variable a, type diff(f,a) which returns df/da ans = cos(a*x)*x To calculate the second derivatives with respect to x and a, respectively, type diff(f,2) or diff(f,x,2) which return ans = -sin(a*x)*a^26-16 6 Symbolic Math Toolbox Limits The fundamental idea in calculus is to make calculations on functions as a variable "gets close to" or approaches a certain value. Recall that the definition of the derivative is given by a limit f(x + h) – f(x) f′(x) = lim --------------------------------- - h→0 h provided this limit exists. The Symbolic Math Toolbox allows you to compute the limits of functions in a direct manner. The commands syms h n x limit( (cos(x+h) - cos(x))/h,h,0 ) which return ans = -sin(x) and limit( (1 + x/n)^n,n,inf ) which returns ans = exp(x) illustrate two of the most important limits in mathematics: the derivative (in this case of cos x) and the exponential function. While many limits lim f ( x ) x→a are "two sided" (that is, the result is the same whether the approach is from the right or left of a), limits at the singularities of f(x) are not. Hence, the three limits, 1 1 1 lim -- , lim -- , and lim -- - - - x→0 x x → 0- x x → 0+ x yield the three distinct results: undefined, - ∞ , and + ∞ , respectively.6-20 CalculusIn contrast to differentiation, symbolic integration is a more complicated task.A number of difficulties can arise in computing the integral. Theantiderivative, F, may not exist in closed form; it may define an unfamiliarfunction; it may exist, but the software can't find the antiderivative; thesoftware could find it on a larger computer, but runs out of time or memory onthe available machine. Nevertheless, in many cases, MATLAB can performsymbolic integration successfully. For example, create the symbolic variables syms a b theta x y n x1 uThis table illustrates integration of expressions containing those variables. f int(f) x^n x^(n+1)/(n+1) y^(-1) log(y) n^x 1/log(n)*n^x sin(a*theta+b) -cos(a*theta+b)/a exp(-x1^2) 1/2*pi^(1/2)*erf(x1) 1/(1+u^2) atan(u)The last example shows what happens if the toolbox can't find theantiderivative; it simply returns the command, including the variable ofintegration, unevaluated.Definite integration is also possible. The commands int(f,a,b)and int(f,v,a,b)are used to find a symbolic expression for b b ∫a f ( x ) dx and ∫a f ( v ) dvrespectively. 6-23 6 Symbolic Math Toolbox Here are some additional examples. f a, b int(f,a,b) x^7 0, 1 1/8 1/x 1, 2 log(2) log(x)*sqrt(x) 0, 1 -4/9 exp(-x^2) 0, inf 1/2*pi^(1/2) bessel(1,z) 0, 1 -besselj(0,1)+1 For the Bessel function (besselj) example, it is possible to compute a numerical approximation to the value of the integral, using the double function. The command a = int(besselj(1,z),0,1) returns a = -besselj(0,1)+1 and the command a = double(a) returns a = 0.23480231344203 Integration with Real Constants One of the subtleties involved in symbolic integration is the "value" of various parameters. For example, the expression – ( kx ) 2 e is the positive, bell shaped curve that tends to 0 as x tends to ±∞ for any real number k. An example of this curve is depicted below with6-24 6 Symbolic Math Toolbox ∞ – ( kx ) 2 ∫ e dx –∞ in the Symbolic Math Toolbox, using the commands syms x k; f = exp(-(k*x)^2); int(f,x,-inf,inf) results in the output Definite integration: Cant determine if the integral is convergent. Need to know the sign of --> k^2 Will now try indefinite integration and then take limits. Warning: Explicit integral could not be found. ans = int(exp(-k^2*x^2),x= -inf..inf) In the next section, you well see how to make k a real variable and therefore k2 positive. Real Variables via sym Notice that Maple is not able to determine the sign of the expression k^2. How does one surmount this obstacle? The answer is to make k a real variable, using the sym command. One particularly useful feature of sym, namely the real option, allows you to declare k to be a real variable. Consequently, the integral above is computed, in the toolbox, using the sequence syms k real int(f,x,-inf,inf) which returns ans = signum(k)/k*pi^(1/2) Notice that k is now a symbolic object in the MATLAB workspace and a real variable in the Maple kernel workspace. By typing clear k6-26 Calculusyou only clear k in the MATLAB workspace. To ensure that k has no formalproperties (that is, to ensure k is a purely formal variable), type syms k unrealThis variation of the syms command clears k in the Maple workspace. You canalso declare a sequence of symbolic variables w, y, x, z to be real, using syms w x y z realIn this case, all of the variables in between the words syms and real areassigned the property real. That is, they are real variables in the Mapleworkspace.Symbolic SummationYou can compute symbolic summations, when they exist, by using the symsumcommand. For example, the p-series 1 1 1 + ----- + ----- + … - - 2 2 2 3adds to π2/6, while the geometric series 1 + x + x2 + ... adds to 1/(1-x), provided|x| < 1. Three summations are demonstrated below. syms x k s1 = symsum(1/k^2,1,inf) s2 = symsum(x^k,k,0,inf) s1 = 1/6*pi^2 s2 = -1/(x-1) 6-27 6 Symbolic Math Toolbox Extended Calculus Example The function 1 f ( x ) = ----------------------------- - 5 + 4 cos ( x ) provides a starting point for illustrating several calculus operations in the toolbox. It is also an interesting function in its own right. The statements syms x f = 1/(5+4*cos(x)) store the symbolic expression defining the function in f. The function ezplot(f) produces the plot of f(x) as shown below. 1/(5+4*cos(x)) 1 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 −6 −4 −2 0 2 4 6 x The ezplot function tries to make reasonable choices for the range of the x-axis and for the resulting scale of the y-axis. Its choices can be overridden by an additional input argument, or by subsequent axis commands. The default6-30 Calculusdomain for a function displayed by ezplot is -2π ≤ x ≤ 2π. To produce a graphof f(x) for a ≤ x ≤ b, type ezplot(f,[a b])Let's now look at the second derivative of the function f. f2 = diff(f,2) f2 = 32/(5+4*cos(x))^3*sin(x)^2+4/(5+4*cos(x))^2*cos(x)Equivalently, we can type f2 = diff(f,x,2). The default scaling in ezplotcuts off part of f2's graph. Set the axes limits manually to see the entirefunction. ezplot(f2) axis([-2*pi 2*pi -5 2]) 32/(5+4*cos(x))^3*sin(x)^2+4/(5+4*cos(x))^2*cos(x) 2 1 0−1−2−3−4−5 −6 −4 −2 0 2 4 6 x 6-31 Calculuseach of whose entries is a zero of f(x). The command format; % Default format of 5 digits zr = double(z)converts the zeros to double form. zr = 0 0+ 2.4381i 0- 2.4381i 2.4483 -2.4483So far, we have found three real zeros and two complex zeros. However, a graphof f3 shows that we have not yet found all its zeros. ezplot(f3) hold on; plot(zr,0*zr,ro) plot([-2*pi,2*pi], [0,0],g-.); title(Zeros of f3) 6-33 6 Symbolic Math Toolbox This is certainly not the original expression for f(x). Let's look at the difference f(x) - g(x). d = f - g pretty(d) 1 8 –––––––––––– + ––––––––––––––– 5 + 4 cos(x) 2 tan(1/2 x) + 9 We can simplify this using simple(d) or simplify(d). Either command produces ans = 1 This illustrates the concept that differentiating f(x) twice, then integrating the result twice, produces a function that may differ from f(x) by a linear function of x. Finally, integrate f(x) once more. F = int(f) The result F = 2/3*atan(1/3*tan(1/2*x)) involves the arctangent function.6-40 CalculusThough F(x) is the antiderivative of a continuous function, it is itselfdiscontinuous as the following plot shows. ezplot(F) 2/3*atan(1/3*tan(1/2*x)) 10.80.60.40.2 00.20.40.60.8−1 −6 −4 −2 0 2 4 6 xNote that F(x) has jumps at x = ± π. This occurs because tan x is singular atx = ± π. 6-41 6 Symbolic Math Toolbox In fact, as ezplot(atan(tan(x))) shows, the numerical value of atan(tan(x))differs from x by a piecewise constant function that has jumps at odd multiples of π/2. atan(tan(x)) 1.5 1 0.5 0 −0.5 −1 −1.5 −6 −4 −2 0 2 4 6 x To obtain a representation of F(x) that does not have jumps at these points, we must introduce a second function, J(x), that compensates for the discontinuities. Then we add the appropriate multiple of J(x) to F(x) J = sym(round(x/(2*pi))); c = sym(2/3*pi); F1 = F+c*J F1 = 2/3*atan(1/3*tan(1/2*x))+2/3*pi*round(1/2*x/pi)6-42 Calculusand plot the result. ezplot(F1,[-6.28,6.28])This representation does have a continuous graph. 2/3*atan(1/3*tan(1/2*x))+2/3*pi*round(1/2*x/pi) 2.5 2 1.5 1 0.5 0−0.5 −1−1.5 −2−2.5 −6 −4 −2 0 2 4 6 xNotice that we use the domain [-6.28, 6.28] in ezplot rather than the defaultdomain [-2π, 2π]. The reason for this is to prevent an evaluation ofF1 = 2/3 atan(1/3 tan 1/2 x) at the singular points x = -π and x = π where thejumps in F and J do not cancel out one another. The proper handling of branchcut discontinuities in multivalued functions like arctan x is a deep and difficultproblem in symbolic computation. Although MATLAB and Maple cannot dothis entirely automatically, they do provide the tools for investigating suchquestions. 6-43 6 Symbolic Math Toolbox Simplifications and Substitutions There are several functions that simplify symbolic expressions and are used to perform symbolic substitutions. Simplifications Here are three different symbolic expressions. syms x f = x^3-6*x^2+11*x-6 g = (x-1)*(x-2)*(x-3) h = x*(x*(x-6)+11)-6 Here are their prettyprinted forms, generated by pretty(f), pretty(g), pretty(h) 3 2 x - 6 x + 11 x - 6 (x - 1) (x - 2) (x - 3) x (x (x - 6) + 11) - 6 These expressions are three different representations of the same mathematical function, a cubic polynomial in x. Each of the three forms is preferable to the others in different situations. The first form, f, is the most commonly used representation of a polynomial. It is simply a linear combination of the powers of x. The second form, g, is the factored form. It displays the roots of the polynomial and is the most accurate for numerical evaluation near the roots. But, if a polynomial does not have such simple roots, its factored form may not be so convenient. The third form, h, is the Horner, or nested, representation. For numerical evaluation, it involves the fewest arithmetic operations and is the most accurate for some other ranges of x. The symbolic simplification problem involves the verification that these three expressions represent the same function. It also involves a less clearly defined objective — which of these representations is "the simplest"?6-44 Simplifications and SubstitutionsThis toolbox provides several functions that apply various algebraic andtrigonometric identities to transform one representation of a function intoanother, possibly simpler, representation. These functions are collect,expand, horner, factor, simplify, and simple.collectThe statement collect(f)views f as a polynomial in its symbolic variable, say x, and collects all thecoefficients with the same power of x. A second argument can specify thevariable in which to collect terms if there is more than one candidate. Here area few examples. f collect(f) (x-1)*(x-2)*(x-3) x^3-6*x^2+11*x-6 x*(x*(x-6)+11)-6 x^3-6*x^2+11*x-6 (1+x)*t + x*t 2*x*t+t 6-45 Simplifications and SubstitutionssimplifyThe simplify function is a powerful, general purpose tool that applies anumber of algebraic identities involving sums, integral powers, square rootsand other fractional powers, as well as a number of functional identitiesinvolving trig functions, exponential and log functions, Bessel functions,hypergeometric functions, and the gamma function. Here are some examples. f simplify(f) x∗(x∗(x-6)+11)-6 x^3-6∗x^2+11∗x-6 (1-x^2)/(1-x) x+1 (1/a^3+6/a^2+12/a+8)^(1/3) ((2*a+1)^3/a^3)^(1/3) syms x y positive log(x∗y) log(x)+log(y) exp(x) ∗ exp(y) exp(x+y) besselj(2,x) + besselj(0,x) 2/x*besselj(1,x) gamma(x+1)-x*gamma(x) 0 cos(x)^2 + sin(x)^2 1simpleThe simple function has the unorthodox mathematical goal of finding asimplification of an expression that has the fewest number of characters. Ofcourse, there is little mathematical justification for claiming that oneexpression is "simpler" than another just because its ASCII representation isshorter, but this often proves satisfactory in practice.The simple function achieves its goal by independently applying simplify,collect, factor, and other simplification functions to an expression andkeeping track of the lengths of the results. The simple function then returnsthe shortest result.The simple function has several forms, each returning different output. Theform simple(f) 6-49 Simplifications and SubstitutionsThis form is useful when you want to check, for example, whether the shortestform is indeed the simplest. If you are not interested in how simple achievesits result, use the form f = simple(f)This form simply returns the shortest expression found. For example, thestatement f = simple(cos(x)^2+sin(x)^2)returns f = 1If you want to know which simplification returned the shortest result, use themultiple output form. [F, how] = simple(f)This form returns the shortest result in the first variable and the simplificationmethod used to achieve the result in the second variable. For example, thestatement [f, how] = simple(cos(x)^2+sin(x)^2)returns f = 1 how = combineThe simple function sometimes improves on the result returned by simplify,one of the simplifications that it tries. For example, when applied to the 6-51 Simplifications and SubstitutionsNext, substitute the symbol S into E with E = subs(E,S,S) E = [ S, 0, 0] [ 0, -S, 0] [ 0, 0, b+c+a]Now suppose we want to evaluate v at a = 10. We can do this using the subscommand. subs(v,a,10)This replaces all occurrences of a in v with 10. [ -(10+S-b)/(10-c), -(10-S-b)/(10-c), 1] [ -(b-c-S)/(10-c), -(b-c+S)/(10-c), 1] [ 1, 1, 1]Notice, however, that the symbolic expression represented by S is unaffected bythis substitution. That is, the symbol a in S is not replaced by 10. The subscommand is also a useful function for substituting in a variety of values forseveral variables in a particular expression. Let's look at S. Suppose that inaddition to substituting a = 10, we also want to substitute the values for 2 and10 for b and c, respectively. The way to do this is to set values for a, b, and c inthe workspace. Then subs evaluates its input using the existing symbolic anddouble variables in the current workspace. In our example, we first set a = 10; b = 2; c = 10; subs(S) ans = 8 6-57 Variable-Precision ArithmeticVariable-Precision Arithmetic Overview There are three different kinds of arithmetic operations in this toolbox. • Numeric MATLAB's floating-point arithmetic • Rational Maple's exact symbolic arithmetic • VPA Maple's variable-precision arithmetic For example, the MATLAB statements format long 1/2+1/3 use numeric computation to produce 0.83333333333333 With the Symbolic Math Toolbox, the statement sym(1/2)+1/3 uses symbolic computation to yield 5/6 And, also with the toolbox, the statements digits(25) vpa(1/2+1/3) use variable-precision arithmetic to return .8333333333333333333333333 The floating-point operations used by numeric arithmetic are the fastest of the three, and require the least computer memory, but the results are not exact. The number of digits in the printed output of MATLAB's double quantities is controlled by the format statement, but the internal representation is always the eight-byte floating-point representation provided by the particular computer hardware. In the computation of the numeric result above, there are actually three roundoff errors, one in the division of 1 by 3, one in the addition of 1/2 to the 6-61 6 Symbolic Math Toolbox result of the division, and one in the binary to decimal conversion for the printed output. On computers that use IEEE floating-point standard arithmetic, the resulting internal value is the binary expansion of 5/6, truncated to 53 bits. This is approximately 16 decimal digits. But, in this particular case, the printed output shows only 15 digits. The symbolic operations used by rational arithmetic are potentially the most expensive of the three, in terms of both computer time and memory. The results are exact, as long as enough time and memory are available to complete the computations. Variable-precision arithmetic falls in between the other two in terms of both cost and accuracy. A global parameter, set by the function digits, controls the number of significant decimal digits. Increasing the number of digits increases the accuracy, but also increases both the time and memory requirements. The default value of digits is 32, corresponding roughly to floating-point accuracy. The Maple documentation uses the term "hardware floating-point" for what we are calling "numeric" or "floating-point" and uses the term "floating-point arithmetic" for what we are calling "variable-precision arithmetic." Example: Using the Different Kinds of Arithmetic Rational Arithmetic By default, the Symbolic Math Toolbox uses rational arithmetic operations, i.e., Maple's exact symbolic arithmetic. Rational arithmetic is invoked when you create symbolic variables using the sym function. The sym function converts a double matrix to its symbolic form. For example, if the double matrix is A = 1.1000 1.2000 1.3000 2.1000 2.2000 2.3000 3.1000 3.2000 3.3000 its symbolic form, S = sym(A), is S = [11/10, 6/5, 13/10] [21/10, 11/5, 23/10] [31/10, 16/5, 33/10]6-62 Variable-Precision ArithmeticFor this matrix A, it is possible to discover that the elements are the ratios ofsmall integers, so the symbolic representation is formed from those integers.On the other hand, the statement E = [exp(1) sqrt(2); log(3) rand]returns a matrix E = 2.71828182845905 1.41421356237310 1.09861228866811 0.21895918632809whose elements are not the ratios of small integers, so sym(E) reproduces thefloating-point representation in a symbolic form. [3060513257434037*2^(-50), 3184525836262886*2^(-51)] [2473854946935174*2^(-51), 3944418039826132*2^(-54)]Variable-Precision NumbersVariable-precision numbers are distinguished from the exact rationalrepresentation by the presence of a decimal point. A power of 10 scale factor,denoted by e, is allowed. To use variable-precision instead of rationalarithmetic, create your variables using the vpa function.For matrices with purely double entries, the vpa function generates therepresentation that is used with variable-precision arithmetic. Continuing onwith our example, and using digits(4), applying vpa to the matrix S vpa(S)generates the output S = [1.100, 1.200, 1.300] [2.100, 2.200, 2.300] [3.100, 3.200, 3.300]and with digits(25) F = vpa(E) 6-63 6 Symbolic Math Toolbox generates F = [2.718281828459045534884808, 1.414213562373094923430017] [1.098612288668110004152823, .2189591863280899719512718] Converting to Floating-Point To convert a rational or variable-precision number to its MATLAB floating-point representation, use the double function. In our example, both double(sym(E)) and double(vpa(E)) return E. Another Example The next example is perhaps more interesting. Start with the symbolic expression f = sym(exp(pi*sqrt(163))) The statement double(f) produces the printed floating-point value 2.625374126407687e+17 Using the second argument of vpa to specify the number of digits, vpa(f,18) returns 262537412640768744. whereas vpa(f,25) returns 262537412640768744.0000000 We suspect that f might actually have an integer value. This suspicion is reinforced by the 30 digit value, vpa(f,30) 262537412640768743.9999999999996-64 Variable-Precision ArithmeticFinally, the 40 digit value, vpa(f,40) 262537412640768743.9999999999992500725944shows that f is very close to, but not exactly equal to, an integer. 6-65 6 Symbolic Math Toolbox Linear Algebra Basic Algebraic Operations Basic algebraic operations on symbolic objects are the same as operations on MATLAB objects of class double. This is illustrated in the following example. The Givens transformation produces a plane rotation through the angle t. The statements syms t; G = [cos(t) sin(t); -sin(t) cos(t)] create this transformation matrix. G = [ cos(t), sin(t) ] [ -sin(t), cos(t) ] Applying the Givens transformation twice should simply be a rotation through twice the angle. The corresponding matrix can be computed by multiplying G by itself or by raising G to the second power. Both A = G*G and A = G^2 produce A = [cos(t)^2-sin(t)^2, 2*cos(t)*sin(t)] [ -2*cos(t)*sin(t), cos(t)^2-sin(t)^2] The simple function A = simple(A)6-66 Linear AlgebraAll three of these results, the inverse, the determinant, and the solution to thelinear system, are the exact results corresponding to the infinitely precise,rational, Hilbert matrix. On the other hand, using digits(16), the command V = vpa(hilb(3))returns [ 1., .5000000000000000, .3333333333333333] [.5000000000000000, .3333333333333333, .2500000000000000] [.3333333333333333, .2500000000000000, .2000000000000000]The decimal points in the representation of the individual elements are thesignal to use variable-precision arithmetic. The result of each arithmeticoperation is rounded to 16 significant decimal digits. When inverting thematrix, these errors are magnified by the matrix condition number, which forhilb(3) is about 500. Consequently, inv(V)which returns [ 9.000000000000082, -36.00000000000039, 30.00000000000035] [-36.00000000000039, 192.0000000000021, -180.0000000000019] [ 30.00000000000035, -180.0000000000019, 180.0000000000019]shows the loss of two digits. So does det(V)which gives .462962962962958e-3and Vbwhich is [ 3.000000000000041] [-24.00000000000021] [ 30.00000000000019]Since H is nonsingular, the null space of H null(H) 6-69 Linear Algebraand inv(H)produces an error message ??? error using ==> inv Error, (in inverse) singular matrixbecause H is singular. For this matrix, Z = null(H) and C = colspace(H) arenontrivial. Z = [ 1] [ -4] [10/3] C = [ 0, 1] [ 1, 0] [6/5, -3/10]It should be pointed out that even though H is singular, vpa(H) is not. For anyinteger value d, setting digits(d)and then computing det(vpa(H)) inv(vpa(H))results in a determinant of size 10^(-d) and an inverse with elements on theorder of 10^d.EigenvaluesThe symbolic eigenvalues of a square matrix A or the symbolic eigenvalues andeigenvectors of A are computed, respectively, using the commands E = eig(A) [V,E] = eig(A) 6-71 6 Symbolic Math Toolbox The variable-precision counterparts are E = eig(vpa(A)) [V,E] = eig(vpa(A)) The eigenvalues of A are the zeros of the characteristic polynomial of A, det(A-x*I), which is computed by poly(A) The matrix H from the last section provides our first example. H = [8/9, 1/2, 1/3] [1/2, 1/3, 1/4] [1/3, 1/4, 1/5] The matrix is singular, so one of its eigenvalues must be zero. The statement [T,E] = eig(H) produces the matrices T and E. The columns of T are the eigenvectors of H. T = [ 1, 28/153+2/153*12589^(1/2), 28/153-2/153*12589^(12)] [ -4, 1, 1] [ 10/3, 92/255-1/255*12589^(1/2), 292/255+1/255*12589^(12)] Similarly, the diagonal elements of E are the eigenvalues of H. E = [0, 0, 0] [0, 32/45+1/180*12589^(1/2), 0] [0, 0, 32/45-1/180*12589^(1/2)] It may be easier to understand the structure of the matrices of eigenvectors, T, and eigenvalues, E, if we convert T and E to decimal notation. We proceed as follows. The commands Td = double(T) Ed = double(E)6-72 6 Symbolic Math Toolbox The commands p = poly(R); pretty(factor(p)) produce 2 2 2 x (x - 1020) (x - 1020 x + 100)(x - 1040500) (x - 1000) The characteristic polynomial (of degree 8) factors nicely into the product of two linear terms and three quadratic terms. We can see immediately that four of the eigenvalues are 0, 1020, and a double root at 1000. The other four roots are obtained from the remaining quadratics. Use eig(R) to find all these values [ 0] [ 1020] [510+100*26^(1/2)] [510-100*26^(1/2)] [ 10*10405^(1/2)] [ -10*10405^(1/2)] [ 1000] [ 1000] The Rosser matrix is not a typical example; it is rare for a full 8-by-8 matrix to have a characteristic polynomial that factors into such simple form. If we change the two "corner" elements of R from 29 to 30 with the commands S = R; S(1,8) = 30; S(8,1) = 30; and then try p = poly(S) we find p = 40250968213600000+51264008540948000*x- 1082699388411166000*x^2+4287832912719760*x^-3- 5327831918568*x^4+82706090*x^5+5079941*x^6- 4040*x^7+x^86-74 Linear AlgebraWe also find that factor(p) is p itself. That is, the characteristic polynomialcannot be factored over the rationals.For this modified Rosser matrix F = eig(S)returns F = [ -1020.0532142558915165931894252600] [ -.17053529728768998575200874607757] [ .21803980548301606860857564424981] [ 999.94691786044276755320289228602] [ 1000.1206982933841335712817075454] [ 1019.5243552632016358324933278291] [ 1019.9935501291629257348091808173] [ 1020.4201882015047278185457498840]Notice that these values are close to the eigenvalues of the original Rossermatrix. Further, the numerical values of F are a result of Maple's floating-pointarithmetic. Consequently, different settings of digits do not alter the numberof digits to the right of the decimal place.It is also possible to try to compute eigenvalues of symbolic matrices, but closedform solutions are rare. The Givens transformation is generated as the matrixexponential of the elementary matrix A = 0 1 –1 0The Symbolic Math Toolbox commands syms t A = sym([0 1; -1 0]); G = expm(t*A)return [ cos(t), sin(t)] [ -sin(t), cos(t)] 6-75 Linear Algebra how = combineNotice the first application of simple uses simplify to produce a sum of sinesand cosines. Next, simple invokes radsimp to produce cos(t) + i*sin(t) forthe first eigenvector. The third application of simple uses convert(exp) tochange the sines and cosines to complex exponentials. The last application ofsimple uses simplify to obtain the final form.Jordan Canonical FormThe Jordan canonical form results from attempts to diagonalize a matrix by asimilarity transformation. For a given matrix A, find a nonsingular matrix V,so that inv(V)*A*V, or, more succinctly, J = VA*V, is "as close to diagonal aspossible." For almost all matrices, the Jordan canonical form is the diagonalmatrix of eigenvalues and the columns of the transformation matrix are theeigenvectors. This always happens if the matrix is symmetric or if it hasdistinct eigenvalues. Some nonsymmetric matrices with multiple eigenvaluescannot be diagonalized. The Jordan form has the eigenvalues on its diagonal,but some of the superdiagonal elements are one, instead of zero. The statement J = jordan(A)computes the Jordan canonical form of A. The statement [V,J] = jordan(A)also computes the similarity transformation. The columns of V are thegeneralized eigenvectors of A.The Jordan form is extremely sensitive to perturbations. Almost any change inA causes its Jordan form to be diagonal. This makes it very difficult to computethe Jordan form reliably with floating-point arithmetic. It also implies that Amust be known exactly (i.e., without round-off error, etc.). Its elements must beintegers, or ratios of small integers. In particular, the variable-precisioncalculation, jordan(vpa(A)), is not allowed. 6-77 Linear Algebra ( A – λ 2 I )v 4 = v 3 ( A – λ 1 I )v 2 = v 1Singular Value DecompositionOnly the variable-precision numeric computation of the singular valuedecomposition is available in the toolbox. One reason for this is that theformulas that result from symbolic computation are usually too long andcomplicated to be of much use. If A is a symbolic matrix of floating-point orvariable-precision numbers, then S = svd(A)computes the singular values of A to an accuracy determined by the currentsetting of digits. And [U,S,V] = svd(A);produces two orthogonal matrices, U and V, and a diagonal matrix, S, so that A = U*S*V;Let's look at the n-by-n matrix A with elements defined by A(i,j) = 1/(i-j+1/2)For n = 5, the matrix is [ 2 -2 -2/3 -2/5 -2/7] [2/3 2 -2 -2/3 -2/5] [2/5 2/3 2 -2 -2/3] [2/7 2/5 2/3 2 -2] [2/9 2/7 2/5 2/3 2]It turns out many of the singular values of these matrices are close to π.The most obvious way of generating this matrix is for i=1:n for j=1:n A(i,j) = sym(1/(i-j+1/2)); end end 6-79 6 Symbolic Math Toolbox The most efficient way to generate the matrix is [J,I] = meshgrid(1:n); A = sym(1./(I - J+1/2)); Since the elements of A are the ratios of small integers, vpa(A) produces a variable-precision representation, which is accurate to digits precision. Hence S = svd(vpa(A)) computes the desired singular values to full accuracy. With n = 16 and digits(30), the result is S = [ 1.20968137605668985332455685357 ] [ 2.69162158686066606774782763594 ] [ 3.07790297231119748658424727354 ] [ 3.13504054399744654843898901261 ] [ 3.14106044663470063805218371924 ] [ 3.14155754359918083691050658260 ] [ 3.14159075458605848728982577119 ] [ 3.14159256925492306470284863102 ] [ 3.14159265052654880815569479613 ] [ 3.14159265349961053143856838564 ] [ 3.14159265358767361712392612384 ] [ 3.14159265358975439206849907220 ] [ 3.14159265358979270342635559051 ] [ 3.14159265358979323325290142781 ] [ 3.14159265358979323843066846712 ] [ 3.14159265358979323846255035974 ] There are two ways to compare S with pi, the floating-point representation of π. In the vector below, the first element is computed by subtraction with variable-precision arithmetic and then converted to a double. The second element is computed with floating-point arithmetic. format short e [double(pi*ones(16,1)-S) pi-double(S)]6-80 Linear AlgebraThe results are 1.9319e+00 1.9319e+00 4.4997e-01 4.4997e-01 6.3690e-02 6.3690e-02 6.5521e-03 6.5521e-03 5.3221e-04 5.3221e-04 3.5110e-05 3.5110e-05 1.8990e-06 1.8990e-06 8.4335e-08 8.4335e-08 3.0632e-09 3.0632e-09 9.0183e-11 9.0183e-11 2.1196e-12 2.1196e-12 3.8846e-14 3.8636e-14 5.3504e-16 4.4409e-16 5.2097e-18 0 3.1975e-20 0 9.3024e-23 0Since the relative accuracy of pi is pi*eps, which is 6.9757e-16, either columnconfirms our suspicion that four of the singular values of the 16-by-16 exampleequal π to floating-point accuracy.Eigenvalue TrajectoriesThis example applies several numeric, symbolic, and graphic techniques tostudy the behavior of matrix eigenvalues as a parameter in the matrix isvaried. This particular setting involves numerical analysis and perturbationtheory, but the techniques illustrated are more widely applicable.In this example, we consider a 3-by-3 matrix A whose eigenvalues are 1, 2, 3.First, we perturb A by another matrix E and parameter t: A → A + tE. As t 6-81 Linear Algebraeigenvalues may vary from one machine to another, but on a typicalworkstation, the statements format long e = eig(A)produce e = 0.99999999999642 2.00000000000579 2.99999999999780Of course, the example was created so that its eigenvalues are actually 1, 2, and3. Note that three or four digits have been lost to roundoff. This can be easilyverified with the toolbox. The statements B = sym(A); e = eig(B) p = poly(B) f = factor(p)produce e = [1, 2, 3] p = x^3-6*x^2+11*x-6 f = (x-1)*(x-2)*(x-3)Are the eigenvalues sensitive to the perturbations caused by roundoff errorbecause they are "close together"? Ordinarily, the values 1, 2, and 3 would beregarded as "well separated." But, in this case, the separation should be viewedon the scale of the original matrix. If A were replaced by A/1000, theeigenvalues, which would be .001, .002, .003, would "seem" to be closertogether.But eigenvalue sensitivity is more subtle than just "closeness." With a carefullychosen perturbation of the matrix, it is possible to make two of its eigenvalues 6-83 6 Symbolic Math Toolbox coalesce into an actual double root that is extremely sensitive to roundoff and other errors. One good perturbation direction can be obtained from the outer product of the left and right eigenvectors associated with the most sensitive eigenvalue. The following statement creates E = [130,-390,0;43,-129,0;133,-399,0] the perturbation matrix E = 130 -390 0 43 -129 0 133 -399 0 The perturbation can now be expressed in terms of a single, scalar parameter t. The statements syms x t A = A+t*E replace A with the symbolic representation of its perturbation. A = [-149+130*t, -50-390*t, -154] [ 537+43*t, 180-129*t, 546] [ -27+133*t, -9-399*t, -25] Computing the characteristic polynomial of this new A p = poly(A) gives p = x^3-6*x^2+11*x-t*x^2+492512*t*x-6-1221271*t Prettyprinting pretty(collect(p,x)) shows more clearly that p is a cubic in x whose coefficients vary linearly with t. 3 2 x + (- t - 6) x + (492512 t + 11) x - 6 - 1221271 t6-84 6 Symbolic Math Toolbox One way to find τ is based on the fact that, at a double root, both the function and its derivative must vanish. This results in two polynomial equations to be solved for two unknowns. The statement sol = solve(p,diff(p,x)) solves the pair of algebraic equations p = 0 and dp/dx = 0 and produces sol = t: [4x1 sym] x: [4x1 sym] Find τ now by tau = double(sol.t(2)) which reveals that the second element of sol.t is the desired value of τ. format short tau = 7.8379e-07 Therefore, the second element of sol.x sigma = double(sol.x(2)) is the double eigenvalue sigma = 1.5476 Let's verify that this value of τ does indeed produce a double eigenvalue at σ = 1.5476. To achieve this, substitute τ for t in the perturbed matrix A(t) = A + tE and find the eigenvalues of A(t). That is, e = eig(double(subs(A,t,tau))) e = 1.5476 1.5476 2.9047 confirms that σ = 1.5476 is a double eigenvalue of A(t) for t = 7.8379e-07.6-88 Solving EquationsSolving Equations Solving Algebraic Equations If S is a symbolic expression, solve(S) attempts to find values of the symbolic variable in S (as determined by findsym) for which S is zero. For example, syms a b c x S = a*x^2 + b*x + c; solve(S) uses the familiar quadratic formula to produce ans = [1/2/a*(-b+(b^2-4*a*c)^(1/2))] [1/2/a*(-b-(b^2-4*a*c)^(1/2))] This is a symbolic vector whose elements are the two solutions. If you want to solve for a specific variable, you must specify that variable as an additional argument. For example, if you want to solve S for b, use the command b = solve(S,b) which returns b = -(a*x^2+c)/x Note that these examples assume equations of the form f(x) = 0. If you need to solve equations of the form f(x) = q(x), you must use quoted strings. In particular, the command s = solve(cos(2*x)+sin(x)=1) 6-89 6 Symbolic Math Toolbox The solutions for a reside in the "a-field" of S. That is, S.a produces ans = [ -1] [ 3] Similar comments apply to the solutions for u and v. The structure S can now be manipulated by field and index to access a particular portion of the solution. For example, if we want to examine the second solution, we can use the following statement s2 = [S.a(2), S.u(2), S.v(2)] to extract the second component of each field. s2 = [ 3, 5, -4] The following statement M = [S.a, S.u, S.v] creates the solution matrix M M = [ -1, 1, 0] [ 3, 5, -4] whose rows comprise the distinct solutions of the system. Linear systems of simultaneous equations can also be solved using matrix division. For example, clear u v x y syms u v x y S = solve(x+2*y-u, 4*x+5*y-v); sol = [S.x;S.y]6-92 Solving Equationsand A = [1 2; 4 5]; b = [u; v]; z = Abresult in sol = [ -5/3*u+2/3*v] [ 4/3*u-1/3*v] z = [ -5/3*u+2/3*v] [ 4/3*u-1/3*v]Thus s and z produce the same solution, although the results are assigned todifferent variables.Single Differential EquationThe function dsolve computes symbolic solutions to ordinary differentialequations. The equations are specified by symbolic expressions containing theletter D to denote differentiation. The symbols D2, D3, ... DN, correspond to thesecond, third, ..., Nth derivative, respectively. Thus, D2y is the Symbolic MathToolbox equivalent of d2y/dt2. The dependent variables are those preceded by Dand the default independent variable is t. Note that names of symbolicvariables should not contain D. The independent variable can be changed fromt to some other symbolic variable by including that variable as the last inputargument.Initial conditions can be specified by additional equations. If initial conditionsare not specified, the solutions contain constants of integration, C1, C2, etc.The output from dsolve parallels the output from solve. That is, you can calldsolve with the number of output variables equal to the number of dependentvariables or place the output in a structure whose fields contain the solutionsof the differential equations. 6-93 6 Symbolic Math Toolbox Example 1 The following call to dsolve dsolve(Dy=1+y^2) uses y as the dependent variable and t as the default independent variable. The output of this command is ans = tan(t+C1) To specify an initial condition, use y = dsolve(Dy=1+y^2,y(0)=1) This produces y = tan(t+1/4*pi) Notice that y is in the MATLAB workspace, but the independent variable t is not. Thus, the command diff(y,t) returns an error. To place t in the workspace, type syms t. Example 2 Nonlinear equations may have multiple solutions, even when initial conditions are given. x = dsolve((Dx)^2+x^2=1,x(0)=0) results in x = [-sin(t)] [ sin(t)] Example 3 Here is a second order differential equation with two initial conditions. The commands y = dsolve(D2y=cos(2*x)-y,y(0)=1,Dy(0)=0, x) simplify(y)6-94 A MATLAB Quick Reference Introduction This appendix lists the MATLAB functions as they are grouped in the Help Desk by subject. Each table contains the function names and brief descriptions. For complete information about any of these functions, refer to the Help Desk and either: • Select the function from the MATLAB Functions list (By Subject or By Index), or • Type the function name in the Go to MATLAB function field and click Go. Note If you are viewing this book from the Help Desk, you can click on any function name and jump directly to the corresponding MATLAB function page.A-2 A MATLAB Quick ReferenceCharacter String Functions String to Number ConversionThis set of functions lets you manipulate strings char Create character array (string)such as comparison, concatenation, search, and int2str Integer to string conversionconversion. mat2str Convert a matrix into a string num2str Number to string conversionGeneral sprintf Write formatted data to a stringabs Absolute value and complex sscanf Read string under format magnitude controleval Interpret strings containing str2double Convert string to MATLAB expressions double-precision valuereal Real part of complex number str2num String to number conversionstrings MATLAB string handling Radix ConversionString Manipulation bin2dec Binary to decimal numberdeblank Strip trailing blanks from the conversion end of a string dec2bin Decimal to binary numberfindstr Find one string within another conversionlower Convert string to lower case dec2hex Decimal to hexadecimal numberstrcat String concatenation conversionstrcmp Compare strings hex2dec IEEE hexadecimal to decimal number conversionstrcmpi Compare strings ignoring case hex2num Hexadecimal to double numberstrjust Justify a character array conversionstrmatch Find possible matches for a string Low-Level File I/O Functionsstrncmp Compare the first n characters of two strings The low-level file I/O functions allow you to openstrrep String search and replace and close files, read and write formatted andstrtok First token in string unformatted data, operate on files, and perform other specialized file I/O such as reading andstrvcat Vertical concatenation of strings writing images and spreadsheets.symvar Determine symbolic variables in an expression File Opening and Closingtexlabel Produce the TeX format from a character string fclose Close one or more open filesupper Convert string to upper case fopen Open a file or obtain information about open filesA-14 Bitwise FunctionsUnformatted I/O Specialized File I/O (Continued)fread Read binary data from file wk1read Read a Lotus123 WK1 spreadsheet file into a matrixfwrite Write binary data to a file wk1write Write a matrix to a Lotus123 WK1 spreadsheet fileFormatted I/Ofgetl Return the next line of a file as a Bitwise Functions string without line terminator(s)fgets Return the next line of a file as a These functions let you operate at the bit level string with line terminator(s) such as shifting and complementing.fprintf Write formatted data to filefscanf Read formatted data from file Bitwise Functions bitand Bit-wise ANDFile Positioning bitcmp Complement bitsfeof Test for end-of-file bitor Bit-wise ORferror Query MATLAB about errors in bitmax Maximum floating-point integer file input or output bitset Set bitfrewind Rewind an open file bitshift Bit-wise shiftfseek Set file position indicator bitget Get bitftell Get file position indicator bitxor Bit-wise XORString Conversion Structure Functionssprintf Write formatted data to a string Structures are arrays whose elements can holdsscanf Read string under format any MATLAB data type such as text, numeric control arrays, or other structures. You access structure elements by name. Use the structure functions toSpecialized File I/O create and operate on this array type.dlmread Read an ASCII delimited file into a matrix Structure Functionsdlmwrite Write a matrix to an ASCII deal Deal inputs to outputs delimited file fieldnames Field names of a structurehdf HDF interface getfield Get field of structure arrayimfinfo Return information about a rmfield Remove structure fields graphics file setfield Set field of structure arrayimread Read image from graphics file struct Create structure arrayimwrite Write an image to a graphics file struct2cell Structure to cell arraytextread Read formatted data from text conversion file A-15 A MATLAB Quick ReferenceObject Functions Multidimensional Array FunctionsUsing the object functions you can create objects, cat Concatenate arraysdetect objects of a given class, and return the class flipdim Flip array along a specifiedof an object. dimension ind2sub Subscripts from linear indexObject Functions ipermute Inverse permute the dimensionsclass Create object or return class of of a multidimensional array object ndgrid Generate arrays forisa Detect an object of a given class multidimensional functions and interpolationCell Array Functions ndims Number of array dimensions permute Rearrange the dimensions of aCell arrays are arrays comprised of cells, which can multidimensional arrayhold any MATLAB data type such as text, numeric reshape Reshape arrayarrays, or other cell arrays. Unlike structures, you shiftdim Shift dimensionsaccess these cells by number. Use the cell arrayfunctions to create and operate on these arrays. squeeze Remove singleton dimensions sub2ind Single index from subscriptsCell Array Functionscell Create cell array Plotting and Data Visualizationcellfun Apply a function to each element This extensive set of functions gives you the ability in a cell array to create basic graphs such as bar, pie, polar, andcellstr Create cell array of strings from three-dimensional plots, and advanced graphs character array such as surface, mesh, contour, and volumecell2struct Cell array to structure array visualization plots. In addition, you can use these conversion functions to control lighting, color, view, and manycelldisp Display cell array contents other fine manipulations.cellplot Graphically display the structure of cell arrays Basic Plots and Graphsnum2cell Convert a numeric array into a bar Vertical bar chart cell array barh Horizontal bar chart hist Plot histogramsMultidimensional Array Functions hold Hold current graphThese functions provide a mechanism for working loglog Plot using log-log scaleswith arrays of dimension greater than 2. pie Pie plot plot Plot vectors or matrices. polar Polar coordinate plot semilogx Semi-log scale plotA-16 B Symbolic Math Toolbox Quick Reference Introduction This appendix lists the Symbolic Math Toolbox functions that are available in the Student Version of MATLAB & Simulink. For complete information about any of these functions, use the Help Desk and either: • Select the function from the Symbolic Math Toolbox Functions, or • Select Online Manuals and view the Symbolic Math Toolbox User's Guide. Note All of the functions listed in Symbolic Math Toolbox Functions are available in the Student Version of MATLAB & Simulink except maple, mapleinit, mfun, mfunlist, and mhelp.B-2
677.169
1
Staten Island Algebra 2 lot of models and analogies that help explain some abstract concepts and help visualize tiniest atoms and molecules and their interactions. Finally, I encourage students to work on additional assignments to enhance their experience and strengthen their problem-solving skills; learn to as...
677.169
1
Calculus and Analytic Geometry 2 Credits: 5Catalog #20804232 Calculus and Analytic Geometry 2 is designed for students of mathematics, science, and engineering. Topics covered include the techniques of integration, numerical approximation of definite integrals, applications of integration and an introduction to first order differential equations, analysis of infinite sequences and series, parametric equations and derivatives of parametric curves, polar coordinates in the plane and integrals using polar coordinates, the analytic geometry of the conic sections, an introduction to vectors in two and three dimensions, scalar and vector cross products, graphs of quadratic surfaces. Course Offerings last updated: 09:02:12 course may make use of an online homework system. Your instructor may choose to use a variety of teaching methods and tools including 'online math software, active learning principles, supplemental video lessons, etc..' Please contact your instructor prior to the first day of class for details about specific approaches to be used in this class sectionAn online subscription to MyMathLab ( is required for this course. Online interactive educational systems provide additional homework support, immediate feedback, and automated grading on many required assignments. Publishers often include an access code in the price of a new textbook, but these can also be purchased separately. In most cases, the subscription will include electronic access to the textbook, so there is no need to purchase a paper copy of the textbook for this class. Please consult your instructor for more information. This section of Calc 2 uses primarily the "inverted classroom" model. Students are responsible for watching roughly three video lectures on-line (via Blackboard or YouTube) per week before class. Class time is spent doing example problems, group work, applications and skill-building. There will be in-class quizzes most Fridays and three to four in-class exams
677.169
1
Essential Calculus 9780495014423 ISBN: 0495014427 Edition: 1 Pub Date: 2006 Publisher: Thomson Learning Summary: This book is a response to those instructors who feel that calculus textbooks are too big. In writing the book James Stewart asked himself: What is essential for a three-semester calculus course for scientists and engineers? Stewart's ESSENTIAL CALCULUS offers a concise approach to teaching calculus, focusing on major concepts and supporting those with precise definitions, patient explanations, and carefully graded p...roblems. ESSENTIAL CALCULUS is about two-thirds the size of Stewart's other calculus texts (Calculus, Fifth Edition and Calculus, Early Transcendentals, Fifth Edition) and yet it contains almost all of the same topics. The author achieved this relative brevity mainly by condensing the exposition and by putting some of the features on the web site Despite the reduced size of the book, there is still a modern flavor: Conceptual understanding and technology are not neglected, though they are not as prominent as in Stewart's other books. ESSENTIAL CALCULUS has been written with the same attention to detail, eye for innovation, and meticulous accuracy that have made Stewart's textbooks the best-selling calculus texts in the world. Stewart, James is the author of Essential Calculus, published 2006 under ISBN 9780495014423 and 0495014427. Three hundred sixty nine Essential Calculus textbooks are available for sale on ValoreBooks.com, two hundred two used from the cheapest price of $0.01, or buy new starting at $530495014427 New, Unread Copy with school stamp on 3 sides. This is Student US Edition. All reference pages included. May be publisher overstock. Might have minor shelf wear on [more] 0495014427 New, Unread Copy with school stamp on 3 sides. This is Student US Edition. All reference pages included. May be publisher overstock. Might have minor shelf wear on covers. Same day shipping with free tracking number. Expedited shipping available. A+ Customer Service![
677.169
1
0764142062 Edition Description: Revised ISBN-13: 9780764142062 Publication Year: 2009 Author: Johanna Holm Language: English Format: Trade Paper ISBN: 9780764142062 Detailed item info SynopsisProduct DescriptionFrom the Inside Flap (back cover) A solid review of math basics emphasizes topics that appear most frequently on the GED: number operations and number sense; measurement; geometry; algebra, functions and patterns; data analysis; statistics and probability Hundreds of exercises with answers A diagnostic test and four practice tests with answers Questions reflect math questions on the actual GED in format and degree of difficulty Paperback: 240 pages Publisher: Barron's Educational Series; 3.0 edition (August 1, 2009) Language: English ISBN-10: 0764142062 ISBN-13: 978-0764142062 We can not ship to Puerto Rico, Alaska, US Terrirtories, PO Boxes, or APO'Ss for the selected shipping rate for this listing. Order Tracking: You will receive an email with the tracking number once shipped It will be automatically updated on your Paypal transaction page All Merchandise is Guaranteed 100% to be as represented in description. If you have any questions or any issues with your purchase please email us prior to
677.169
1
Find a Lonetree, CO Algebra 1Elementary math includes number theory, which is the study of whole numbers and relations between them. Things like factors, multiples, primes, composites, divisibility tests, and exponents provide a critical basis for later mathematical understanding. This may be the most important subject for
677.169
1
MathGrapher is a stand-out graphing tool designed for students, scientists and engineers. Visitors can read the Introduction to get started, as it contains information about the various functions that the tool can... This course, presented by MIT and taught by Professor Denis Auroux, presents multivariable calculus. It is intended for use in a freshman calculus course. It includes material relating to vectors and matrices, partial... This is a basic course, produced by Gilbert Strang of the Massachusetts Institute of Technology, on matrix theory and linear algebra. Emphasis is given to topics that will be useful in other disciplines, including... Created by Lewis Blake and David Smith for the Connected Curriculum Project, the purposes of this module are to experiment with matrix operations, espcially multiplication, inversion, and determinants, and to explore...
677.169
1
Calculus : Single and Multivariable - 5th edition Summary: Calculus teachers recognize Calculus as the leading resource among the ''reform'' projects that employ the rule of four and streamline the curriculum in order to deepen conceptual understanding. The fifth edition uses all strands of the ''Rule of Four'' - graphical, numeric, symbolic/algebraic, and verbal/applied presentations - to make concepts easier to understand. The book focuses on exploring fundamental ideas rather than comprehensive coverage of multiple similar cases that are ...show morenot fundamentally unique. Readers will also gain access to WileyPLUS, an online tool that allows for extensive drills and practice. Calculus teachers will build on their understanding in the field and discover new ways to present concepts to their students89148208
677.169
1
Text: R. Larson and R.P. Hostetler Precalculus, Houghton Mifflin Company 7th Edition Supplies: A spiral notebook of graph paper for notes. A cheap scientific calculator with buttons for sin, cos, tan, Ln, and Log. Homework: Approximately 2 hours of homework will be assigned each meeting and additional review assignments will be given on weekends. Most faculty will be checking whether the homework is completed while students do classwork. Odd problems have answers in the back so students can check their work before proceeding to the next problem. Working with study partners can make homework easier and more fun. Math Lab: All students should plan on spending at least an hour a week at the Math Lab in Gillet 222. Be sure to have someone look over your homework to see if you are doing it correctly as an answer which matches the one in the back of the book doesn't guarantee you are doing things correctly.
677.169
1
Mathematical Application in Agriculture - 2nd edition Summary: Get the specialized math skills you need to be successful in today's farming industry with MATHEMATICAL APPLICATIONS IN AGRICULTURE, 2nd Edition. Invaluable in any area of agriculture-from livestock and dairy production to horticulture and agronomy--this easy to follow book gives you steps by step instructions on how to address problems in the field using math and logic skills. Clearly written and thoughtfully organized, the stand-alone chapters on mathematics involved in crop produc...show moretion, livestock production, and financial management allow you to focus on those topics specific to your area while useful graphics, case studies, examples, and sample problems to help you hone your critical thinking skills and master the93
677.169
1
Why is Eulers method to solving (numerically) DE's included on the new AP syllabus? It seems (with calculator in hand) that slope fields are numrically/graphically sufficient. What have I missed about Eulers method that should give it such "weighty" status on the new syllabus? Are there plans to review, evaluate and if needed modify the new syllabus by ETS?
677.169
1
SparkCharts-created by Harvard students for students everywhere-serve as study companions and reference tools that cover a wide range of high school, college, and gradu...show moreate school subjects, including math, business, history, computer programming, medicine, law, foreign language, humanities, and science. Titles like Spanish Vocabulary, Microsoft Excel, Study Tactics, the Bible, Algebra I, Chemistry, and Literary Terms give you what it takes to find success in school and beyond. Outlines and summaries cover key points, while diagrams and tables make difficult concepts easier to digest. ...show lessEdition/Copyright: 05 Cover: Paperback Publisher: Sparkchart
677.169
1
books.google.com - This book bridges the gap between the many elementary introductions to set theory that are available today and the more advanced, specialized monographs. The authors have taken great care to motivate concepts as they are introduced. The large number of exercises included make this book especially suitable... Modern Set Theory: The basics
677.169
1
4th and 5th grade students. Not a C Minus is a comprehensive study aid for senior high school Mathematics. It covers topics such as calculus, probability, finance and trigonometry, and uses a conversational, informal teaching style. Every topic is explained in detail, with sample questions and worked solutions. Practice and hone important addition skills with this second bookThis book was written by an experienced maths tutor to help parents and carers to be able to tutor their child in general maths. This book contains 14 lesson plans for hourly tuition sessions (which would cost £20-£25 if you paid a tutor)on maths units ranging from basic addition to more advanced ratio questions. Also suitable for adults taking basic or functional skills exams in adult numeracy. Practice and hone important subtraction skills with this second book subtraction skills addition skillsPractice and hone important multiplication skills. Select one of twenty math problems with complete solutions that instruct the student in the multiplication process. The book also includes four bonus word problems with complete explanations and answers. Easily navigate the links from the problem list to view the solution. Most appropriate for 4th and 5th grade studentsOne of the best ways to succeed in Geometry is to practice taking real test questions. This volume contains 133 problems on Three-Dimensional Figures divided into four chapters: Definitions and Shapes; Rectangular Solids; Cylinders, Cones, Spheres; and Prisms and Pyramids. Try the problems. With a little Practice, Practice, Practice, you'll be Perfect, Perfect, Perfect. Good Luck!!
677.169
1
for Physicists This best-selling title provides in one handy volume the essential mathematical tools and techniques used to solve problems in physics. It is a vital ...Show synopsisThis best-selling title provides in one handy volume the essential mathematical tools and techniques used to solve problems in physics. It is a vital addition to the bookshelf of any serious student of physics or research professional in the field. The authors have put considerable effort into revamping this new edition. * Updates the leading graduate-level text in mathematical physics * Provides comprehensive coverage of the mathematics necessary for advanced study in physics and engineering * Focuses on problem-solving skills and offers a vast array of exercises * Clearly illustrates and proves mathematical relations New in the Sixth Edition: * Updated content throughout, based on users' feedback * More advanced sections, including differential forms and the elegant forms of Maxwell's equations * A new chapter on probability and statistics * More elementary sections have been deleted Mathematical Methods for Physicists The book covers a very large range of mathematical issues. Some topics are well developed, like the ones covering complex analysis, while others, like the group theory, are much concise (in my opinion). In general, the book offers a good introduction to several topics, not only for the physicists
677.169
1
mat... read more Numerical Methods by Germund Dahlquist, Åke Björck Practical text strikes balance between students' requirements for theoretical treatment and the needs of practitioners, with best methods for both large- and small-scale computing. Many worked examples and problems. 1974 edition. Mathematical Tools for Physics by James Nearing Encouraging students' development of intuition, this original work begins with a review of basic mathematics and advances to infinite series, complex algebra, differential equations, Fourier series, and more. 2010 editionA First Course in Numerical Analysis: Second Edition by Anthony Ralston, Philip Rabinowitz Outstanding text, oriented toward computer solutions, stresses errors in methods and computational efficiency. Problems — some strictly mathematical, others requiring a computer — appear at the end of each chapter. Product Description: Bonus Editorial Feature: Richard W. Hamming: The Computer Icon Richard W. Hamming (1915–1998) was first a programmer of one of the earliest digital computers while assigned to the Manhattan Project in 1945, then for many years he worked at Bell Labs, and later at the Naval Postgraduate School in Monterey, California. He was a witty and iconoclastic mathematician and computer scientist whose work and influence still reverberates through the areas he was interested in and passionate about. Three of his long-lived books have been reprinted by Dover: Numerical Methods for Scientists and Engineers, 1987; Digital Filters, 1997; and Methods of Mathematics Applied to Calculus, Probability and Statistics, 2004. In the Author's Own Words: "The purpose of computing is insight, not numbers." "There are wavelengths that people cannot see, there are sounds that people cannot hear, and maybe computers have thoughts that people cannot think." "Whereas Newton could say, 'If I have seen a little farther than others, it is because I have stood on the shoulders of giants, I am forced to say, 'Today we stand on each other's feet.' Perhaps the central problem we face in all of computer science is how we are to get to the situation where we build on top of the work of others rather than redoing so much of it in a trivially different way." "If you don't work on important problems, it's not likely that you'll do important work." — Richard W. Hamming
677.169
1
TI-89 WORKSHEET 1: Basic Algebra Concepts i TI-89 BASICS To begin, you need to be able to find the ´˜button. It is in the lower left hand corner of the calculator.. Jhildreth ti89 ws 1 basics algebra concepts pdf. Shape Of Polynomial Functions Worksheet. Shape Of Polynomial Functions Worksheet. Newark k12 ny us 74420819213937360 lib 74420819213937360 files basic skills ws packet pdf. Basic Skills Worksheets To jump to a location in this book 1. Click a bookmark on the left. To print a part of the book 1. Click the Print button..
677.169
1
Perfect for students of all backgrounds and interest levels, Pride and Ferrellsll need to succeed in todaysGoing beyond standard mathematical physics textbooks by integrating the mathematics with the associated physical content, this book presents mathematical topics with their applications to physics as well as basic physics topics linked to mathematical techniques. It is aimed at first–year graduate students, it is much more concise and discusses selected topics in full without omitting any steps. It covers the mathematical skills needed throughout common graduate level courses in physics and features around 450 end–of–chapter problems, with solutions available to lecturers from the Wiley website.
677.169
1
More About This Textbook Overview Mathematical concepts and theories underpin engineering and many of the physical sciences. Yet many engineering and science students find math challenging and even intimidating. The fourth edition of Mathematical Techniques provides a complete course in mathematics, covering all the essential topics with which a physical sciences or engineering student should be familiar. By breaking the subject into small, modular chapters, the book introduces and builds on concepts in a progressive, carefully-layered way - always with an emphasis on using math to the best effect, rather than relying on theoretical proofs. With a huge array of end of chapter problems and new self-check questions, the fourth edition of Mathematical Techniques provides extensive opportunities for students to exercise and enhance their mathematical knowledge and skills. Distinctive Features - Over 500 worked out examples offer the reader valuable guidance when tackling problems. - Self-check questions and over 2,000 end of chapter problems provide extensive opportunities for students to actively master the concepts presented. - A series of projects at the end of the book encourage students to use mathematical software to further their understanding. - An Online Resource Centre features additional resources for lecturers and students, including figures from the book in electronic format, ready to download; a downloadable solutions manual featuring worked solutions to all end of chapter problems (password protected); and mathematical-based programs relating to the projects featured at the end of the book
677.169
1
Tutorials on Mathematics to MATLAB Written for science and engineering students, this book provides an introduction to basic mathematics problems using MATLAB. Topics covered include programming in MATLAB, matrix fundamentals, statistics, and differential and integral calculus. MATLAB is introduced and used to solve numerous examples throughout the book.
677.169
1
Instructions: Read pages 307-317 of Chapter 5 to learn about angles in trigonometry. Pay particular attention to the new form of angle measure, the radian. A complete grasp of this concept will serve you well through the remainder of the course. Also note that this reading covers the material in subunits 1.2.1 through 1.2.5. Instructions: Read pages 321-330 of Chapter 5 to learn points on circles using sine and cosine. The unit circle is one of the key concepts in trigonometry, and a complete understanding how the coordinates from the equation of the circle are used to create the trig functions is fundamental to understanding the derivations of the graphs of the functions and all the useful identities we will study in later sections. Committing the unit circle to memory is a useful skill. This reading covers the material in subunits 1.3.1 through 1.3.4. Instructions: Read pages 333-338 of Chapter 5 to learn about the other trigonometric functions and some important identities, establishing some relationships between all six of the trigonometric functions. This reading covers the material in subunits 1.4.1 through 1.4.3. Instructions: The graphs of the sinusoidal functions have some important features that help us construct them, and make them useful for modeling. Read pages 353-365 to gain an understanding of the properties of these graphs. This reading also covers the topics outlined in subunits 2.1.1 through 2.1.5. Instructions: Much like the sinusoidal functions, the remaining trig function graphs have some key features that are important to understand. Read pages 369- 374 to understand these. This reading selection covers the topics outlined in subunits 2.2.1 through 2.2.4. Instructions: The functions give us some powerful tools for equation solving. Read pages 379–384 to begin to understand them, their graphs, and their relationship to the trig functions. This reading covers the topics outlined in subunits 2.3.1 through 2.3.3. Instructions: Now that you have an understanding of the inverse trig functions and the domains and ranges of both the trig and inverse trig functions, you can begin solving more complicated equations. Read pages 387-394 to understand how. This reading covers the topics outlined in subunits 2.4.1 and 2.4.2. Instructions: Trigonometry is very useful for modeling real world data. Read the selection on pages 397–403 to develop some modeling techniques. Note that this reading covers the topics outlined in subunits 2.5.1 and 2.5.2. Instructions: Because real world phenomena are often modeled with trig functions, it is important to understand how changes to the functions affect the resulting graphs and the phenomena being modeled. To increase your understanding of this, read pages 442–448 of Chapter 7. This selection also covers the topics outlined in subunits 3.4.1 through 3.4.3. Instructions: Pages 451–466 introduce the idea of using trigonometric functions in triangles other than right triangles. Read this selection carefully. This selection also covers the topics outlined in subunits 4.1.1 and 4.1.2. Instructions: Read the selection from pages 467–475. The selection defines a new system for graphing points and curves based on distances and angles rather than the horizontal and vertical distances used in the Cartesian Coordinate system. This reading covers the topics outlined in subunits 4.2.1 through 4.2.3. Instructions: Vectors are geometric objects with both distance and direction, and they have numerous applications. Read pages 491-502 from Chapter 8 carefully to understand these applications. This reading selection also covers the topics outlined in subunits 4.4.1 through 4.4.3. Instructions: Up until this point in the course, we have been defining functions in terms of two variables: a dependent and an independent variable. Parametric equations give us a new way to define functions, determining the coordinates of a point based on functions of a third variable, often time. Read pages 504–512 to learn about these concepts. This reading also covers the topics outlined for subunits 4.5.1 through 4.5.3.
677.169
1
Sample Worksheet: Algebraic Shortcuts for the SAT, GRE, GMAT Most students taking the SAT, GRE, or GMAT know their algebra fairly well, but many find they can't complete all the problems in the allowed time. Why? It's NOT because those students are just naturally slow: it's because they're doing more work than they need to! It's not their speed but their very approach --- the very way they conceive of the process of problem-solving --- that's flawed. To ace the math sections of standardized tests, you have to learn how to attack problems in new ways so that you get the right answers by doing as little work as possible! (Part of the reason so many students don't already know how to do this is that it's not taught well throughout middle and high school math classes. Learning how to think quickly and deeply often requires UNLEARNING habits your math teachers instilled in you in school!) To see if you're up to par, try the following problems, which test your ability to make deep algebraic connections that will save you time. If your algebraic skills are what they really should be, you should be able to do all the problems in TWENTY SECONDS OR LESS! If you can't, send me an email and start working with me today! EXERCISE SET: ALGEBRAIC SHORTCUTS Suppose 2x+7=19. Find the value of each of the following expressions WITHOUT solving for x!
677.169
1
Infinite Algebra worksheets and tests with exactly the types of questions you want in just minutes. No more writing questions by hand, searching through old books and worksheets, or wading through a database of prewritten questions. Unlike other test generators, Infinite Algebra 2 actually creates the questions for you. You select the parameters for each question: the size of the numbers; types of numbers; the types of operations involved; and the number of steps. Our software chooses the variables and numbers for each question so the questions conform to the options you picked. Because the questions are written on-the-fly, you won't run out of suitable questions. You can create multiple versions of tests, vary the difficulty of questions, and change your assignments from year to year to adapt to your individual classes. Prepare your examples, class work, homework, and tests without ever running out of good material. Other features include: easily-controlled spacing, free-response and multiple-choice format, scale, merge, export, and a presentation mode to use while teaching (compatible with LCD projectors and other display systems). Invented by a math teacher, Infinite Algebra 2 covers all major Algebra 2 topics, from multi-step equations to trigonometric identities. All questions are completely customizable. Suitable for all levels from remedial to advanced. What's new in this version: New: Preference for notation for greatest integer function New: Added maximize/restore button to Presentation View Improved: Help files Improved: Scroll bars Improved: User interface Improved: When choices make a question too tall for a page, some choices are removed
677.169
1
Asvab Math? Answer ASVAB mathematics can be scary and difficult for some, but there are many exercises and ways to prepare for the assessment. The ASVAB mathematics portion may include algebra equations, fractions, exponent problems, inequalities, and the need to know the different types of numbers. For a complete list of what you may find on the ASVAB mathematics portion, see this link:
677.169
1
Learn Math Interactive Differential Equations (IDE) — CODEE IDE is available, for free, at When we first, in the 1990s, became acquainted with Hubert Hohn and his wonderful interactive illustrations we knew immediately that he had found a real key to making our subject (and many others) come alive--not only for students, but for ourselves and our faculty colleagues. Hohn is a master educator. Ordinary Differential Equations - Resources The sources below are among some of the best locations of sites dedicated to ordinary differential equations, online and on the computer. General Sources Math Forum: Differential Equations. Daniel Kopsas Daniel Kopsas (pronounced "Copsis") E-mail: [email protected] Office Phone: (417) 447 - 8263 Twitter: I teach mathematics at Ozarks Technical Community College in Springfield, Missouri. I was inspired by Maria Andersen from Muskegon Community College to create this site and continue to pursue the use of technology in the mathematics classroom. For each of the courses in the sidebar to the left, I have built or I am currently building math video libraries. Statistics Correlation examples Statistics is an applied branch of Mathematics. A knowledge of statistics is like a knowledge of foreign languages or of algebra; it may prove of use at any time under any circumstances. - A. L. Bowley Courses[edit] Welcome to the Wikibook of Statistics Statistics - Area of applied mathematics concerned with the data collection, analysis, interpretation and presentation. Statistics is used in almost every field of research: the discovery of the Higgs particle, social sciences, climate research,... With this, and with its well established foundations, it is very well suited for a wikibook. Statistics - Wikibooks, collection of open-content textbooks All of Statistics All of Statistics A Concise Course in Statistical Inference by Larry Wasserman Get the book from Springer or Amazon Errata (last updated April 3 2013) New England Complex Systems Institute 238 Main Street Suite 319, Cambridge, MA 02142 Phone: 617-547-4100 Fax: 617-661-7711 Textbook for seminar/course on complex systems.View full text in PDF format The study of complex systems in a unified framework has become recognized in recent years as a new scientific discipline, the ultimate of interdisciplinary fields. Breaking down the barriers between physics, chemistry and biology and the so-called soft sciences of psychology, sociology, economics, and anthropology, this text explores the universal physical and mathematical principles that govern the emergence of complex systems from simple components. Dynamics of Complex Systems September 2007 This is the second installment of a new feature in Plus: the teacher package. Every issue contains a package bringing together all Plus articles about a particular subject from the UK National Curriculum. Whether you're a student studying the subject, or a teacher teaching it, all relevant Plus articles are available to you at a glance. Teacher package: Mathematical Modelling
677.169
1
This series of videos, created by Salman Khan of the Khan Academy, features topics covered from very basic algebra all the way through algebra II. This is the best algebra playlist to start at if you've never seen... This series of videos contains 180 Worked Algebra I examples (problems written by the Monterey Institute of Technology and Education). You should look at the "Algebra" playlist if you've never seen algebra before or if... This lesson helps students understand financial topics (interest rates, FICO scores and loan payments) in a mathematical context. Students will calculate monthly payments for a car or home based on the best interest... This lesson involves economics and mathematical materials. Students will use their knowledge of exponents to compute an investment's worth using a formula and a compound interest simulator. They may also use the model... This algebra unit from illuminations provides an in depth exploration of exponential models in context. The model of light passing through water is used to demonstrate exponential functions and related mathematical...
677.169
1
The first half of the course will focus on first learning how to analyze & reason (through the study of logic) and then moves on to the basics of geometry, being lines & angles. Afterward, the concept of lines & angles is used to understand the principles of polygons such as triangles and quadrilaterals. Finally, the first semester ends with applying the coordinate plane to this basic geometric knowledge. The second half of the course focuses on more advanced topics such as shapes, figures, and their properties. Even more advanced topics will be discussed such as the properties of circles and triangles, trigonometry, and graph theory. Other less intimidating topics such as perimeter, area, volume, and surface area will also be discussed. Additionally, algebra, statistics, and probability will be reviewed in order to prepare students for the mathematical sections of both the College Board and SAT exams. Students will also learn a bit of the history of mathematics such as ancient numeral systems, numerical superstitions, and the biographies of important mathematicians.
677.169
1
Elementary Statistics - With CD - 6th edition Summary: Elementary Statistics is appropriate for a one-semester introductory statistics course, with an algebra prerequisite. ES has a reputation for being thorough and precise, and for using real data extensively. Students find the book readable and clear, and the math level is right for the diverse population that takes the introductory statistics course. The text thoroughly explains and illustrates concepts through an abundance of worked out examplesTEXTBOOKFETCHER! Cortland, NY 0201771306 This is a used item2.10 +$3.99 s/h Good Wonder Book Frederick, MD Good condition. With CD! Writing inside. 6th edition. $2.10 +$3.99 s/h VeryGood Wonder Book Frederick, MD Very Good condition. With CD! 6th edition94
677.169
1
Soal Soal Un Matematika Smp Kelas 9
677.169
1
A pre-calculus class involves using critical thinking skills to analyze a problem, not just coming up with a single answer. Basic algebra, geometry, and trigonometry topics along with their graphs are used as the foundation. The level of difficulty is increased as multiple concepts are related
677.169
1
BEGINNING ALGEBRA 9780131444447 ISBN: 0131444441 Edition: 4 Pub Date: 2004 Publisher: Prentice Hall Summary: Clearly explained concepts, study skills help, and real-life applications will help the reader to succeed in learning algebra. Martin-Gay, K. Elayn is the author of BEGINNING ALGEBRA, published 2004 under ISBN 9780131444447 and 0131444441. Eighty seven BEGINNING ALGEBRA textbooks are available for sale on ValoreBooks.com, sixty two used from the cheapest price of $0.01, or buy new starting at $5 Great condition for a used book! Minimal wear. Experience the best customer ca... [more]Sorry, CD missing. Great condition for a used book! Minimal wear. Experience the best customer care, fast shipping, and a 100% satisfaction guarantee on all orders
677.169
1
Precise Calculator has arbitrary precision and can calculate with complex numbers, fractions, vectors and matrices. Has more than 150 mathematical functions and statistical functions and is programmable (if, goto, print, return, for).
677.169
1
Hutchison's Beginning Algebra (The Hutchison Series in Mathematics) Elementary Algebra, 8/e by Baratto/Bergman is part of the latest offerings in the successful Streeter-Hutchison Series in Mathematics. The fourth edition continues the hallmark approach of encouraging the learning of mathematics by focusing its coverage on mastering math through practice. This worktext seeks to provide carefully detailed explanations and accessible pedagogy to introduce beginning and intermediate algebra concepts and put the content in context. The authors use a three-pronged approach (I. Communication, II. Pattern Recognition, and III. Problem Solving) to present the material and stimulate critical thinking skills. Items such as Math Anxiety boxes, Check Yourself exercises, and Activities represent this approach and the underlying philosophy of mastering math through practice. The exercise sets have been expanded, organized, and clearly labeled. Vocational and professional-technical exercises have been added throughout. Repeated exposure to this consistent structure should help advance the student's skills in relating to mathematics. The book is designed for a combined beginning and intermediate algebra course, or it can be used across two courses, and is appropriate for lecture, learning center, laboratory, or self-paced courses. It is accompanied by numerous useful supplements, including McGraw-Hill's online homework management system, MathZone
677.169
1
... More About This Book the definition of limit, and problems related to the computation of limits. Answers and hints to the test problems are provided, and "road signs" appear in the margins, marking passages requiring particular attention. 1969An Introduction to Theory An excellent introduction to sequences,combinations,and limits. The book introduces the theory underlying these concepts to the reader. Very concise. Numerous problems. The book would make an excellent supplement for any text which emphasizes the concepts listed above. Finally, price is right. Was this review helpful? YesNoThank you for your feedback.Report this reviewThank you, this review has been flagged.
677.169
1
L3.5 Deriving Trig Derivatives Susan Braford, Mathematics Instructor Kings Fork High School, Suffolk Susan Braford created this power point presentation for a classroom activity. The students derived the differentiation rules for the 6 trig functions by using the graphs of sine and cosine, their graphing calculators and what they knew of the reciprocals an ratios. Once they discovered d/dx of sin x was cos x, they then used the quotient rule to discover csc x. She was able to roam about the room with her wireless mouse and monitor their progress. It was the first time she tried this and everything went better than anticipated.
677.169
1
Students Courses Need Help? MATH BRIDGE THE GAP SECOND GRADE PREP This class will prepare students to take the advanced math test in the spring and prepare them to suceed in honors or regular level math in 7th grade. It will cover in depth prealgebra, fractions, percents, decimals, graphing, and inequalities.
677.169
1
The Algebra 1: The Complete Course DVD Series will help students build confidence in their ability to understand and solve algebraic problems. In this episode, students will learn how to derive an algebraic equation using the method of finite differences and how to derive the input/output table of numerical values. Grades 5-9. 30 minutes on DVD.
677.169
1
It supports standard scientific calculator functions, including absolute value, logn, and a wide range of trigonometric functions, including hyperbolic sine, cosine, and tangent! In addition to graphing any expression you can throw at it, it can also plot parametric curves (fun!), functions translated to the y-axis (i.e. functions in the form x=f(y)), and that's not all! It also includes the popular Polynomial Calculator, capable of performing lightning-fast operations on polynomials with any number of variables. Now you can factor polynomials with ease! It has every function you'd expect from a much more expensive graphing calculator, but only costs a fraction of the price, and works on the PPC you already own, so why not save yourself the cost of a Texas Instruments TI-81 or a Casio fx-7700.
677.169
1
Resources For MATLAB Help SCHOOL OF ENGINEERING Need help with MATLAB? MATLAB is a computer program designed for technical calculations. Its name is an abbreviation of "Matrix Laboratory." MATLAB allows users to implement calculations in relatively short programming time. When these calculations have been performed, they can be visualised by means of several plot-routines. If you're just starting out with MATLAB, here are a few useful links: The Eindhoven University of Technology has developed a very nice tutorial for MATLAB. This is good for folks who want to simply jump in with a separate open MATLAB window.
677.169
1
Mathematics for Elementary School TeachersIntended for the one- or two-semester course required of Education majors, Mathematics for Elementary School Teachers, 4/e, offers pre-service teachers a comprehensive mathematics course designed to foster concept development through examples, investigations, and explorations. Visual icons throughout the main text allow instructors to easily connect content to the hands-on activities in the corresponding Explorations Manual. In addition to presenting real-world problems that require active learning, Bassarear demonstrates that there may be many paths to finding a solution--and even more than one answer. With this exposure, future teachers are better prepared to assess student needs using diverse approaches.
677.169
1
Rent Textbook Buy New Textbook Currently Available, Usually Ships in 24-48 Hours $205Combinatorial optimization is a multidisciplinary scientific area, lying in the interface of three major scientific domains: mathematics, theoretical computer science and management. The three volumes of the Combinatorial Optimization series aims to cover a wide range of topics in this area. These topics also deal with fundamental notions and approaches as with several classical applications of combinatorial optimization. Concepts of Combinatorial Optimization, is divided into three parts: On the complexity of combinatorial optimization problems, that presents basics about worst-case and randomized complexity; Classical solution methods, that presents the two most-known methods for solving hard combinatorial optimization problems, that are Branch-and-Bound and Dynamic Programming; Elements from mathematical programming, that presents fundamentals from mathematical programming based methods that are in the heart of Operations Research since the origins of this field.
677.169
1
A bridge to upper-level math, BJU Press' Fundamentals of Math Grade 7 textbook will ensure students have a solid foundation in the skills they'll need for 8th grade and beyond! Whole numbers, decimals, number theory, fractions, rational numbers, percents, measurement, geometry, area/volume, probability/statistics, integers, algebra, relations/functions, and logic/set theory are all taught in detail with review to keep concepts fresh. Integrating biblical principles with "Math in Use" segments, students are taught to see God as involved in all subjects, while problem solving sections allow for thinking skill development as students use problem solving methods to reach a solution. Chapters include clear explanations of new concepts, plenty of practice, "skill check" reviews, example problems, and a cumulative review of the new concept. 676 pages, softcover. Product: Fundamentals of Math 7 StudentText (2nd Edition) Vendor: BJU Press Edition Number: 2 Binding Type: Paperback Minimum Grade: 7th Grade Maximum Grade: 7th Grade Number of Pages: 676 Weight: 3.44 pounds Length: 10.75 inches Width: 8.5 inches Height: 1.5 inches Vendor Part Number: 218933 Subject: Math Fundamentals of Math 7 StudentText (2nd Edition). Average Rating Parent Rating Comments We used the DVD's for BJU. I have to say my children did not find them easy to watch. They felt the instructor was quite boring. My husband felt that a lot of the lessons should have been simplified for better understanding. He often stopped the DVD to teach them an easier way to work the problems.
677.169
1
More About This Textbook Overview This study of chaos, fractals and complex dynamics is intended for anyone familiar with computers. While keeping the mathematics to a simple level with few formulas, the reader is introduced to an area of current scientific research that was scarcely possible until the availability of computers. The book is divided into two main parts; the first provides the most interesting problems, each with a solution in a computer program format. Numerous exercises enable the reader to conduct his or her own experimental work. The second part provides sample programs for specific machine and operating systems; details refer to IBM-PC with MS-DOS and Turbo-Pascal, UNIX 42BSD with Berkeley Pascal and C. Other implementations of the graphics routines are given for the Apple Macintosh, Apple IIE and IIGS and Atari ST
677.169
1
Adobe Reader is required to view and print PDF files. Get Adobe Reader. Clicking on this link will take you to another web site where you can download Adobe Acrobat Reader for free. The site will open in a new window. Online Support for Math Classes The following courses are taught through online resources: Course Code Course Title Math 060 Prealgebra Math 070 Elementary Algebra Math 080 Geometry Math 110 Intermediate Algebra Math 111 Business and Consumer Mathematics Math 114 Applied Mathematics I Math 116 Applied Mathematics II Math 122 Trigonometry Math 125 Quantitative Literacy Math 128 Foundations of Mathematics for Elementary Teachers Math 129 Foundations of Mathematics for Elementary Teachers II Math 140 College Algebra Math 143 Finite Math Math 149 Precalculus Math 250 Calculus Math 251 Calculus II Math 252 Calculus III To access these classes: 1. Navigate to my.oakton.edu (available as the myOakton link on the top of this Web page). Enter your username and password.
677.169
1
CTY Math Coordinator's Handbook Introduction The CTY math staff is a very close, family-like group, and a large number of staff members return year after year. This makes it possible for many of the important details of the mechanics of CTY math to be passed along informally, as a sort of "apprenticeship" which occurs during the course of the summers. Usually, this works beautifully, because most instructors have been TAs, and most coordinators have been instructors. However, when someone lacking this experience is hired as a math coordinator (as has happened a few times), there is no single, comprehensive information source which this person can use as a guide. The pre-calculus instructor's handbook does not cover many aspects of the coordinator's job, and the coordinator's job description is not sufficiently specific. The new coordinator must repeat, in only a few days, the development of methods and ideas that previous math coordinators have already worked out over the course of several years. This is clearly not an efficient training technique! To help new coordinators manage this uncomfortable situation, this handbook gives a detailed explanation of the activities, responsibilities, and overall role of the CTY math coordinator. It discusses some of the major decisions that a coordinator will have to make, and points out aspects of the job which may vary from site to site. Topics are organized by the time period in which they occur. The handbook is pretty useful as a checklist for the experienced coordinator, as well. After all, there's a lot of stuff to remember! Authors The Math Coordinator's Handbook was written by Ari Rapkin, with help and suggestions from Martha Meadows, Mike Brandstein, and Shermann Min. Collectively, their experience as math coordinators spans five CTY sites and a total of nearly twenty years. Beginning of summer Placement testing materials Make sure there are enough ADT's, scantrons, pencils, scrap paper, and scoring keys. Get a timer or a watch with a second hand. Progress checklists, HSST's & keys, textbooks and curriculum spirals If any are missing, have them sent from the central office. Make sure there are a reasonable number of each. Math office Find a convenient place to keep testing materials and extra or shared resources. Remember that tests and valuable things (e.g. graphing calculators) need to be kept secure. Suggested places: coordinator's classroom, the math staff's house/dorm, or an office. Study hall policy This is an annual source of confusion. Sometimes the site-wide studyhall format or location just isn't appropriate for pre-calc, and the math coordinator has to point this out to the site director and say "Let's do this differently.". There are several possible ways to conduct the pre-calc study hall: in dorm rooms, in dorm lounges, in classrooms, in lecture halls, etc. I'm not going to make a specific recommendation. Instead, here are pros & cons: General stuff: Seven hours a day in the same classroom is a long time, and the students enjoy a change of scenery (as do the staff!). Unfortunately, holding study hall anywhere but the regular classroom building means everyone -- staff and students -- has to carry their stuff back and forth every day. Of course, if you're at a commuter site, the students are stuck with this scenario anyhow. Also, few places are as well designed for studying as a classroom. Dorm-room desks may come close, but lecture hall desks are often too small and lounges are simply not on: they're generally poorly lit and not furnished with writing surfaces. Dorm rooms: This is the only study-hall location which allows the students to use their computers. However, distractions abound (including those same computers), and there aren't enough math-staffers or teacher's editions to go around. It's a nuisance for the staff to have to trudge from dorm to dorm with a heavy load of books and folders. Finally, there's no good way to handle evening testing: if you allow testing during study hall, then you have to assign a math staffer to proctor the student(s) in an office or dorm lounge, or else impose on the RA to act as a proctor. Dorm lounges: The whole class is in one place, so the instructor & TA don't have to run a marathon each evening. Unfortunately, other classes have discovered these benefits, so there may be contention for lounges. There's probably a TV and a soda machine to act as distractions. Some lounges are so close to student rooms that they cannot be used if the rooms' residents are present. Also, since the lounge is by definition a casual place, the students feel less bound by rules of classroom behavior. Lecture halls: If the lecture hall is big enough, more than one class can share it. This is good because the staff members can split duties & resources and keep an eye on each others' students, but bad because the large number of students is harder to control (and lecture halls tend to echo). Classrooms: Seven hours a day in the same classroom is too much, but this can be adjusted by holding study hall in a different classroom. If it's in the same building, then everyone can leave their stuff in their regular classroom during the afternoon and overnight. This helps the staff be aware of students who are spending all their free time studying -- they're the ones who take their books home. Post-testing policy Another annual source of confusion: do we allow the students to take HSST's and/or finals after classes are officially over? The possible times include: during the last afternoon (when they're supposed to be packing), the dance that night, or the morning they leave. There are pros and cons to every one of these, and they're very site- dependent because each site schedules its end-of-session activities differently. Choose for yourself. (Consult with the other administrative folks, of course.) What's most important is that you choose early, and see that everyone knows the policy so that confusion doesn't arise at the end of the session. Math staff orientation Take some time during staff orientation to make sure that all the math folks get to know each other. Go do something fun together. (Mandatory Fun! ... and it's your last chance to get off campus) This schedule is straight from the 1992 job description. Alter the timing as appropriate to your site's orientation schedule. Thursday evening: Meet, explore each other's experience and areas of strength. Decide who will work with whom and what courses they will teach (see below for more on this. It can -- and I think should --be put off until everyone's had a day or two to get familiarized with each other and CTY). Friday afternoon: Discuss the history and philosophy of CTY pre-calc. Share past experiences about students and their abilities, instructors and their attitudes toward math and teaching, and the nature of a CTY class. Saturday morning: Focus on pragmatic issues: how to administer a class, where to start students, flexible pacing, appropriate questioning, appropriate progress, and assessment. Study skills workshop Many students have never needed to develop good study skills, and so have an especially difficult time with a self-paced course. Try to arrange with the academic counsellor to offer math study skills workshops. It's useful to have a completely optional one during the first week and another during the second week which you can require that specific students attend. Emphasize to the math staff the importance of paying close attention to the students' study habits, and taking action right away when a problem is noticed. Mattababy The CTY math staff email network. Okay, most of the school-year traffic concerns The Simpsons or sumo, but if you want fast answers from a whole bunch of long-time CTY math staffers, this is the place to ask. During the course of the summer, a lot of useful information goes back and forth. Before (or at the start of) each session Math questionnaires These may be available several days in advance if you're at a Baltimore site. If not, you probably won't have them in your hands for very long before the kids arrive. In any case, take the time to sort through these -- get other math folks to help! -- and determine how many Regents or other Unified-Math students you have, how many geometry-only requests, and a rough estimate of the counts for each subject. It's hard to tell who needs what with the trig-plus courses, but there aren't generally very many students that advanced so they'll end up in the same classroom anyhow. If you're really ambitious, generate a list of pre-calc students for whom you're missing questionnaires (or whose information is unclear). Then flag their registration packets so that you can have them fill out questionnaires when they check in. This requires some coordination with whoever's organizing registration, but it's worth the effort. If you try to get this information after the parents have gone home, your success rate will be much lower. Who teaches what Once you've looked through the questionnaires, you can make a tentative decision about how many sections of each pre-calc course you're going to need. Ask your instructors and TAs what they'd like to teach and who'd like to work together, then try to match up their requests with what you need. You'll probably have to do some shuffling after the placement testing, but with luck most of your tentative plans will hold. Then you can distribute course materials and make up class lists, student folders, etc. It's helpful to pair new staff members with experienced ones. Trying for gender balance is good too, since we're supposed to be role models for the students to identify with. Don't put a great deal of effort into this, though. Pairing people with course content is much more important. RAs and dorms Find out who the math RAs are. Introduce yourself to them, and check that they know the plans for study hall. Make sure the instructors (and TA's, if possible) meet at least their own RAs, if not all of them. Find out which dorms the math kids are in. If you're going to be holding study hall in dorms, get keys to those dorms. Some math RAs are quite comfortable with math, and are willing or even eager to help their students with their work, answer questions during class visits, etc. This is delightful when it happens, and worth encouraging. On the other hand, be alert to RAs who are not so mathematically inclined. Reassure them that this sort of participation is entirely voluntary, and there will be no negative consequences if they opt not to. Course materials and progress records Make sure that the instructors have progress chart masters, and the appropriate textbooks, curriculum spirals, progress checklists, and supplementary materials. Make sure that they know where the rest of these materials are kept. Classrooms See that the instructors know which classrooms they have and get the keys. Find out which keys open which other classrooms. (The ability to swap keys can come in very handy, especially if the TAs don't have their own keys.) If there are multiple classes using the same resources (e.g., two rooms of Algebra II) try to assign them to nearby rooms. Also, if there's an extra classroom nearby, try to get it for use as a testing room. Go to the classrooms (with the other instructors, if possible) and make sure that everything is set up and working. Rearrange furniture, put up posters, try out the overhead projector, etc. There may be restrictions on what you can do to the rooms, so check first. (For example, at Dickinson you can't take extra furniture out of the rooms.) Parent/student orientation Be on hand during as much of orientation as possible, because some parents will be in a hurry and unable to stay until the official question-&-answer time, and since they don't know who's going to be their child's instructor they'll all want to talk to YOU. Keep a notebook handy, since you'll get a lot of placement info from parents. Don't promise a specific placement or instructor, make overly glowing assurances about how much work the student will finish, etc.; if the parents ask these things, explain the placement testing process and repeat the words "self-paced instruction" as necessary. If they ask about residential things, answer what you can but feel free to direct them to the residential dean or someone else who really knows these things. At some sites, the math coordinator talks to the pre-calc parents separately after the all-parents welcome speech. This gives you a chance to introduce the math staff, give a little history of the math program, describe day-to-day events and the rigors of the program, explain what we expect from students and from parents, etc. This is a good time to talk some more about the meta-learning that's going on: even if a kid doesn't finish trig, he or she has learned a good deal about how to learn. Try to keep this speech short, especially at residential sites, because the parents are anxious to get back on the road for the many-hour drive home. In your conversations with parents, and in your speech if you give one, stress the importance of making plans with schools now, instead of waiting until the student comes home or worse, until September. Emphasize the importance of being supportive, but not overly demanding. Point out that not finishing a year's worth of work does not mean that the student failed. Every session, there are a small number of parents who didn't read the course description and are just now discovering that pre-calc is not a group-activity or lecture course. Describe the interactive things we do (extra problems, small-group lectures, students studying together) and if they're still not happy send them to an administrator. There's no need to apologize for providing exactly what was offered. Placement testing (ADT's) When, where, and how the testing happens is really site-dependent. Whether or not there's a Scantron machine to do the scoring is also unpredictable (but "no" is the safer guess). If not, making plastic stencils to go over the Scantron forms speeds things up a lot. Once you've got the tests scored, it's time to match scantrons with questionnaires, and assign kids to classes. This is known as "The Party Game", and usually CTY will spring for pizza and sodas, for sustenance while you tackle this administrative nightmare. Pull all the Geometry kids' scantrons right away (this is why you sorted out their questionnaires earlier!) since their class assignments are independent of their ADT scores. Make sure none of them have really atrocious scores. If any do, they're candidates for an algebra review before beginning Geo. Then split up the rest of the bunch based on ADT scores, school history & plans, Regents/Unified, and your innate good judgment. :-) During each session Progress records Make sure everyone is keeping thorough, detailed records of what the students are doing -- strong areas as well as weak. Checklists can wait, but it wouldn't hurt to update them weekly. Math staff meetings This can be completely informal -- e.g., a chat over lunch -- or you can schedule a time and place. Just make sure that you're not discussing sensitive issues where students might overhear. Try to meet at least twice a week. Observing the other instructors Spend an hour or two in each classroom during the first half of the session. This isn't a real formal thing, but check with the instructor & TA beforehand to see what's a good time. They may have special activities planned. This is a good time to peep at their record-keeping, and to acquire info for staff evaluations. Pay attention to the interactions of staff with students, and of staff with staff (i.e., is the instructor using the TA appropriately?). Afterwards, tell them what you thought, and offer any suggestions or praise that apply. If there were any serious problems, check up later to be sure that improvements have been made. Partner trouble Unfortunately, not every instructor-TA pair gets along perfectly. The staff members need to know that it's okay to disagree, as long as the discussions are held out of earshot of the students. Also, make sure they're aware that they should bring any serious problems to the attention of the coordinator or the academic dean quickly, so that they don't drag on unnecessarily. RA visits to classes For self-paced courses, these visits will be quick. Policy says that each RA is to attend classes 2 hrs/wk, but in self-paced classrooms there's little to see or do, and the RA's presence may in fact be a distraction. Also, pre-calc RAs frequently have students in several classes, and they must split their visitation time accordingly. Student evaluations It's Never Too Early to Start Writing Your Evals. Check with an administrator to make sure you know the little quirks of this year's evaluation format -- it changes every year, sometimes between sessions. Encourage new instructors to go to the how-to session that someone (probably the academic dean) will offer. Distribute sample math evals. Get your own done early so you can worry about other things. Phone calls to families In the middle of the second week, ask all the instructors to review their students' progress and identify those kids who are unlikely to reach whatever goal they've set -- e.g., they've signed up for Algebra II in the fall and aren't going to finish Algebra I. Each instructor should call the families of these students and explain the situation, being very careful to emphasize that the purpose of the call is to allow the family to start making plans for the fall ASAP, not a disciplinary action or an indicator of failure. Anyone who calls a student's family must keep a record of what was said during the conversation. This is helpful not only if problems come up later, but also in making your evaluations and parent-conference conversations more specific. Extra Problems sessions There are a large number of interesting math problems (and computer science, and physics, and chemistry, and ...) which the students will enjoy tackling in their spare time and discussing in class. To many students, this is the best part of the day, so it's well worth a little of the instructors' time to prepare activities. The workload can be kept to a minimum if the staff take turns writing problems. CTY has a collection of suggested problems, but everyone on the math staff is strongly encouraged to bring their own as well. Usually, the problems are handed out one day and discussed the next. The logistics of the discussion group vary from site to site, but the most common set-ups (with pros & cons) are: During the second hour of study hall -- this will require instructor's permission, otherwise kids will go to Extra Problems just to get out of study hall. However, it avoids most of the problems of the other two plans. During an afternoon activity period -- doesn't interfere with class time, but not many kids are going to give up Ultimate to do more math. Even if they're really interested in the problem. On the other hand, kids from other classes might show up. At the end of the afternoon class -- it's tricky to do this in a way that allows kids from different math classrooms to interact. More often, this is done in each classroom separately. Unfortunately, class discussions disrupt those kids who would rather keep working. Tailoring the CTY curriculum Many students in the upper pre-calc classes (those using the Brown Advanced Math book) are trying to place out of a class back home that involves pieces of several CTY courses. If you're lucky, they've brought curricula and/or textbooks from back home so that you'll know what their schools expect. More likely, you'll have to ask them to call home and have information sent (or you may have to make the calls yourself). The best way to handle the curriculum-matching problem is to have the student complete one CTY course (so that he/she will have certified in something), followed by piece-wise study to complete the home-school curriculum. HSST's, scantrons, scoring keys, and testing procedure The tests etc. should be at hand in the coordinator's classroom or some other convenient place. Make sure the instructors and TAs know how and where to administer the tests, and how to score them -- red or green Flair pens only! Also, see that the tests and keys are returned promptly so that they can remain secure. The instructions included with the tests pretty much explain what to do. The two most important things for everyone to remember are: keep an eye on the clock, and have someone else double-check your scoring. End of session Student program evaluations (SPE's) Allow time for these to be filled out on the last or next-to-last day. The last study hall might be a good time. Make sure that the students know this is coming, so that they're not counting on this class time in order to study for or take a final exam. Student evaluations Hassle the other instructors as necessary to get their student evals finished on time. Yes, it's possible to drag out first session evals into second session, but this is a bad idea since there's so much stuff going on for session II. Encourage TA involvement in writing the evals. This doesn't just mean asking the TAs to type up the instructors' scribbled notes, although it's okay to ask for this type of help too. Often the TA gets to know some of the students better than the instructor does, and can give the instructor descriptions of these students' strengths, weaknesses, study habits, etc. This information makes an evaluation more personalized and informative. You may be expected to pre-read the other instructors' evals before they go to an administrator. Don't worry about making them perfect, since your style is almost guaranteed to be slightly different from that of the official reader -- but you can filter out the obvious grammatical, punctuation, and content errors. Staff evaluations Write one for your TA. This will be kept on file for him/her in case of later job-reference requests. You may also be expected to write evals of the other instructors and of the other TAs, or of your math staff in general. There may be examples available. The time limits on writing these are a bit looser, but try to have them done before you leave the site. Progress records, checklists, certification forms Make sure everyone fills out the checklists and cert forms according to whatever directions Baltimore has sent out this year. Don't assume it's the same as last year. It rarely is. Parent conferences TAs are not required to attend, but encourage them to do so. It's good practice if they're thinking of being an instructor. Most of them want to go to the conferences anyhow, so this isn't really an issue. Parents will ask you what courses their children should take next, in regular school or at CTY. Try to have suggestions in mind. However, recognize that some parents will take what you say as gospel instead of discussing it with anyone else. Emphasize the necessity of talking to their home schools, and of considering the student's interests. Most likely, the other instructors can handle all their parents' questions, but let them know that they can send tough ones your way. The same rules apply here as at the beginning of the session: answer what you can, don't make unnecessary promises or apologies, and don't feel compelled to deal with the really far-out cases (send them to an administrator and move along to the next family). Between sessions Departing staff Make sure that staff members who are leaving or switching jobs after first session get all their paperwork done and approved before they go. Find out where they have left classroom keys and teaching materials. Also, see that they've left an address which is valid for the remainder of the summer. Incoming staff members Try to be on hand to greet math staff members arriving between sessions. If you know during first session that people already on site will be joining the math staff during second session, try to meet them and introduce them to other math staffers before Intersession. They may want to borrow books to brush up on their math during first session; if you have books to spare, fire away. It may also be possible to get in touch with session II staff members who are not already on site, especially if they're at another CTY site for session I. This is rarely necessary, but in some cases (e.g., someone won't be arriving until just before placement testing) it becomes reasonable. End of summer Packing up Make sure all the textbooks, curriculum spirals, Regents books, etc. make their way back to Baltimore (or wherever they're going to spend the winter). Baltimore needs an inventory of what's staying on site, if anything.
677.169
1
To log in and use all the features of Khan Academy, please enable JavaScript in your browser. Math Linear algebra Matrices, vectors, vector spaces, transformations, eigenvectors/values. Covers all topics in a first year college linear algebra course. This is an advanced course normally taken by science or engineering majors after taking at least two semesters of calculus (although calculus really isn't a prereq) so don't confuse this with regular high school algebra. This is one of those tutorials that bring many ideas we've been building together into something applicable. Orthogonal projections (which can sometimes be conceptualized as a "vector's shadow" on a subspace if the light source is above it) can be used in fields varying from computer graphics and statistics! If you're familiar with orthogonal complements, then you're ready for this tutorial! Finding a coordinate system boring. Even worse, does it make certain transformations difficult (especially transformations that you have to do over and over and over again)? Well, we have the tool for you: change your coordinate system to one that you like more. Sound strange? Watch this tutorial and it will be less so. Have fun! As we'll see in this tutorial, it is hard not to love a basis where all the vectors are orthogonal to each other and each have length 1 (hey, this sounds pretty much like some coordinate systems you've known for a long time!). We explore these orthonormal bases in some depth and also give you a great tool for creating them: the Gram-Schmidt Process (which would also be a great name for a band). Eigenvectors, eigenvalues, eigenspaces! We will not stop with the "eigens"! Seriously though, eigen-everythings have many applications including finding "good" bases for a transformation (yes, "good" is a technical term in this context).
677.169
1
Introductory Linear Algebra An Applied First Course 9780131437401 ISBN: 0131437402 Edition: 8 Pub Date: 2004 Publisher: Prentice Hall Summary: This book presents an introduction to linear algebra and to some of its significant applications. It covers the essentials of linear algebra (including Eigenvalues and Eigenvectors) and shows how the computer is used for applications.Emphasizing the computational and geometrical aspects of the subject, this popular book covers the following topics comprehensively but not exhaustively: linear equations and matrices an...d their applications; determinants; vectors and linear transformations; real vector spaces; eigenvalues, eigenvectors, and diagonalization; linear programming; and MATLAB for linear algebra.Its useful and comprehensive appendices make this an excellent desk reference for anyone involved in mathematics and computer applications. Kolman, Bernard is the author of Introductory Linear Algebra An Applied First Course, published 2004 under ISBN 9780131437401 and 0131437402. Two hundred twenty Introductory Linear Algebra An Applied First Course textbooks are available for sale on ValoreBooks.com, sixty four used from the cheapest price of $19.72, or buy new starting at $14537401-4-0-3 Orders ship the same or next business day. Expedited shipping within U.S. [more] May include moderately worn cover, writing, markings or slight discoloration. SKU:9780131437401
677.169
1
Elementary Statistics with CD : A Step by Step Approach with Formula Card and Data Cd 9780077460396 ISBN: 0077460391 Edition: 8 Pub Date: 2011 Publisher: McGraw-Hill Higher Education Summary: Be guided through every step of the fundamentals of statistics. It is a great introduction to statistics for college students who have a basic grasp of algebra. It covers all the main concepts effectively and provides a lot of opportunity for practical application. Students are taught problem solving using detailed instructions and examples. It also focuses on the different digital applications used in statistics suc...h as Excel, graphing calculators and MINITAB. It also complements an online course so students can receive more from their course and excellent feedback from the online platform. We offer many top quality used statistics textbooks for college students. Bluman is the author of Elementary Statistics with CD : A Step by Step Approach with Formula Card and Data Cd, published 2011 under ISBN 9780077460396 and 0077460391. Five hundred thirteen Elementary Statistics with CD : A Step by Step Approach with Formula Card and Data Cd textbooks are available for sale on ValoreBooks.com, one hundred thirty seven used from the cheapest price of $73.88, or buy new starting at $173 Comes with CD only. This is an international edition. Brand New 8th Ed. Same Content High Quality Color and Paper as US Edition, International Softcover Edition. Ship within 2 [more] ALTERNATE EDITION: Comes with CD only.
677.169
1
Algebra for Dummies is a comprehensive book teaching about the basics of algebra while making simple all the concepts about it. However, for anyone to fully learn and understand Algebra, there are certain prerequisites that students have to master first. For any student or person to excel in algebra, he or she should be adequately knowledgeable about certain concepts. Knowledge about the proper way of converting one unit into another is one of such requirements. Students should know beforehand how to convert liters into gallons and vice versa. Memorizing the metric to English conversions is also crucial. But that wont be all. Even before one should try to read the Algebra for Dummies book, he should be confident enough to know the right order of operations and the precedence used for mathematical and algebraic expressions. These are where the parentheses, exponents, multiplication, division, addition, and subtraction are involved. Know which numbers you have to evaluate first, given a complicated set of mathematical problem. There is also what is known as the properties of roots, exponents, absolute value, and of the four basic mathematical operations. Everybody getting ready to learn algebra should be familiar with these topics as well. Learning how to convert between percents, decimals, and fractions is necessary also. The fractional equivalent of a percentage and its decimal form should be second nature to students who want to excel in algebra. This is a pre requisite that you can find in several algebra worksheets. Practice your knowledge on these concepts to make algebra a whole lot easier for you. With Algebra for Dummies, how to do algebra do become an easier and a more worthwhile experience. Find yourself enjoying algebra despite its complexity. With this book, mathematics becomes a walk in the park. Algebra is a subject that can be made easy once you learn all the necessary rules and use the right formulas. Some of the concepts of algebra have to be memorized more than understood. Keeping useful algebraic formulas at the back of your mind, ready for access when you need them, would help you speed up the entire process of solving just about any problem. Many algebraic formulas are useful even if you are not solving any word or linear problems at all. As a matter of fact, you can be doing something as ordinary as going on a road trip or planting in your garden and find the need to solve distance problems or area equations. Many of the concepts of algebra can be applied in ones everyday life. And it follows that the many things youll find in Algebra for Dummies will prove to be useful. Memorizing the formulas about area, circumference, distance traveled, simple interest, compounding interest, temperature, the Pythagorean Theorem, and the solution to quadratic equation are going to help you solve even the most complicated algebraic problems in the easiest possible way. Try to tuck these formulas in your mind and youll definitely find algebra a lot simpler than you thought it is. Learning all about the divisibility rules will also make your struggle with algebra a whole lot easier. Algebra for dummies will teach you all about these divisibility rules that would make solving algebraic problems so much faster. Simply memorize them and youll see how simple algebra can really be. Algebra worksheets also come with the book. These worksheets are very useful for practice as it can make a student excel in all the topics explained and illustrated in the book. With Algebra for Dummies, how to do algebra becomes a simple task. Everybody can be a master of it, regardless if youre a student, an employee, or a plain hobbyist. Algebra is not a very easy subject. As a matter of fact, it is one of the most complex subjects that students will encounter during their stay in school. It is such a great thing that Algebra for Dummies is created, which is a very easy-to-follow manual for students to help them understand algebra in a less complicated way. With the book, they will be able to solve a lot of complex problems and still arrive at an accurate solution each time. The book is also designed to increase ones understanding on how to do algebra and the different processes in which it works. The book also includes algebra worksheets that will allow students to practice their new-found understanding of the topics as explained in the book. This book is written by Mary Jane Sterling, an educator who teaches in three academic levels: college, high school, and junior high. Sterling has been in the field of education right after graduating from college, thus giving her all the necessary experiences and opportunities to expound on the different mathematical subjects, more particularly Algebra. Sterling has been teaching for 30 years at Bradley University in Peoria, Illinois. Algebra for Dummies comes in three different versions Algebra for Dummies I, Algebra for Dummies II, and Linear Algebra for Dummies. Each book is divided into different parts or topics so students will be able to understand the different concepts surrounding algebra better. Working on an algebraic equation is a lot easier now, thanks to this book that breaks down the topics into smaller concepts. As such, students need not suffer from information overload. Each book is over 300 pages long, written with the intention of making algebra a very easy subject not just for students but also for professionals, businessmen, hobbyists, and alike. For all of those who find algebra a very challenging subject, Algebra for Dummies is here to help. Let the book teach you how to do algebra in a way that is much easier and simpler for a regular student like you. After reading the book from cover to cover, you wont be vexed by the variables x, y, and z anymore. The plain-English explanation of algebraic concepts will guide you towards the most accurate solutions all the time. Learn algebra explained in the words that you will fully understand. Practice your lessons with the included algebra worksheets so you can solve similar or more complicated problems with full confidence. With this book, you will be able to factor out variables, solve quadratic equations, and find your way through linear equations with full ease. Algebra for Dummies is a pain-free way to learn and ace this subject. First off, students will be taught what numbers are and their different forms. Learn the difference between integers, both positive and negative integers, as well as rational and irrational number. Also, factoring will become a fun method for you with this book. Work yourself through prime numbers and all the concepts of distribution will full ease. Equations will become an easy subject for anybody who is reading the book. The book is filled with many algebra worksheets involving the most common equations encountered under this subject like age problems, distance problems, work problems, and the likes. Solving these equations will be a walk in the park. Lastly, and maybe the most important use of the book is that it will teach readers on how to put into practical use all the algebraic concepts that they have learned. With it, youll be more confident of your measurements, story problems, formulas, and graphs. Algebra can definitely improve your life for the better. Learning algebra might be hard and confusing especially to beginners. But we can be able to remedy this with the use of proper resources that would enable us to learn algebra in easier and faster way. We can refer to these sources as Algebra for Dummies. In this article I will be providing you with some of the best Algebra for Dummies Resources in order for you to find easier ways in learning this subject. Algebra for Dummies: Algebra Websites One of the best and easiest resources to come by is Algebra Websites. These are internet sites that offer the basic and a very comprehensive information in Algebra such as equation solving, graphing and number systems. Some of the best website also offers programs, graphing tools, topic outlines, list of reliable resources and interactive lessons that can greatly help you out, these are also all free, so you dont have to worry about the budget. Sites may also contain algebra games and exercises where you can have fun and learn at the same time. Algebra for Dummies: Online Classes Another thing you can go for is going on free algebra classes online. There are a lot of class websites that offer materials such as downloadable lesson and exercises. There are also site like mathhops.com and algebra-class.com which allow students and teachers to interact through their community forums and share their ideas and questions pertaining to algebra. There are also streamable video lessons that would make you easily understand the topics being discussed. Algebra for Dummies: Algebra Video Tutorials Video tutorials which you can either stream online or download had become a really popular way of learning algebra. Lots of people prefer this type of learning as it makes it very easy to understand and it would feel like you are going to a regular algebra class. The video content is also created in a way to assist the viewers and provide the convenience in making the video lesson easy to grasp and view. Some of the websites you might want to try to get algebra video lessons are mathexpression.com, virtualnerd.com and lots mores. Algebra for Dummies: Books Of course you also can take the traditional method of reading books for granted. In fact it is one of the most convenient methods to do. You can bring a book almost anywhere without any hassle; also you dont need anything else when you have this aside from a properly lit room. The only thing you need to consider when purchasing one is that it should be a right fit for you and your level. Choose a book that makes it easy for you to understand the lessons. One of the best ways to help you out regarding is researching online abut algebra book reviews and what people who are expert in these thing can advice on what particular book would be fit for you. You can even order the book online too so that it you need to go to the bookstore. If you are sitting in your algebra class looking at your book, seeing the numbers, letter and the stuffs you normally find in an equation, you might be asking yourself if it is really necessary to learn algebra. We might typically say that we could avoid jobs dealing with the subject and therefore avoid having to learn it in the first place. However you have to realize that learning algebra can be very important as it has lots of applications in our everyday life though we dont normally notice it. Regarding learning the subject, it might a bit confusing at first but once you get the fundamental concepts you can actually discover that trying to learn it isnt that hard. There are also different ways on how to learn the subject and make it easier. This article algebra for dummies would provide you with great tips a beginner should learn in order to learn the subject. Algebra for Dummies Tip One: Learn your Multiplication Tables One of the most fundamental concepts one should master before delving in the world of algebra is mastering the multiplication table. This is really important as lots of algebraic equations normally use a lot of multiplication than most of the other mathematical operations, thus making it easier for you to understand equations if you are already a master of multiplication. Algebra for Dummies Tip Two: Understand your Lessons by Heart This tip is really important, you need to understand that there are no shortcuts in algebra, and the concepts you learn from the beginning can be used and applied even to very complex equations. Thus, you should not take your basic algebra classes for granted, in fact you should take it a lot more seriously and learn it by heart, since this things will be your foundation in learning the more complex lessons on the subject. By learning the basic concepts by heart you wont ever forget the basics and can have an easier time understanding the more complex stuff. Algebra for Dummies Tip Three: Dont be afraid to ask questions If you are confused about something then ask other people or your instructors about it. Dont be afraid to ask questions because you are still on the process of learning. Keep in mind that the key in learning algebra is understanding the reasons for the different ways the equations acts, and this might be a bit confusing since there are lots of different ways it could act. Thus, ask questions and clear out your understanding. Algebra for Dummies Tip Four: Practice If you want to learn algebra you need to devote time for it. You have to practice and become familiar with how different equations work. You should also take the learning process step by step. Dont be in a hurry; you cant just directly proceed with the complex equations without learning the basic as youd just make your head ache. Start at the easiest until you master it completely before going to the next level. If you are trying to teach your kids algebra, then you have to find a teaching that would be appropriate for their age and thus make them interested and curious in learning the subject. This article will provide with very suitable way in teaching kids algebra. We can refer to it as algebra for dummies! The term algebra was derived the Arabic term al-jabr which means the reunion of broken parts. Some algebraic ideas have already been used even an early as the 1650 B.C in Ancient Babylon and Egypt and thus brought to Europe by the Arabs. Now, in our world today thousands and thousands of year later it is considered as one of the major subjects and foundations of every education. Thus learning it a very important task to get the education you want especially for kids. Here are some great algebra games for kids: Algebra for Dummies: Algebra Bingo This game requires working out certain equations and then marking it off in their bingo board. The teacher will provide equations and the students should work out the answer to the equation and mark it on their boards. Kids would be given a minute or more before moving to the next equation. This allows kids just beginning algebra to work with just a pencil and a paper. Algebra for Dummies: Algebraic Equation Race This is actually a very simple classroom game, but offers the motivation for the students to learn and practice. Its really easy to do, there would be two teams composed of the same number of people, the teacher would then ask algebraic equations and the two teams would race who could answer first, once they are able to give the correct answer they move closer to the finish line, this process is repeated until one completes and finishes. This actually has the element of competitiveness which provides the kids with the motivation to learn their algebra. Algebra for Dummies: Slope of Letters Game This simple activity helps students to recognize the different slopes of common lines found everywhere around them. This game was actually an idea from Jim Wilson from the University of Georgia; the teacher would be explaining the differences between the oblique, negative and positive slope lines. The teacher would then provide a letter and ask the student the lines that make up the letter. Algebra for Dummies: Guess My Point This game is actually a graphing guessing game in which players are given turns to ask others about the different properties of a point in a graph. They players can either ask if the point is either positive or negative, which axis is it located or of it is higher than a specific number or spaces from the axis. These are only one of the many algebra games for dummies that you can try out. This is actually a very good way to motivate kids and other algebra beginners to start learning algebra. This is also a very good way to practice and train the mind to process algebra more quickly. There are lots of people are really weak when it comes to algebra or mathematics. Lots opt to read books attend algebra classes, research the internet or perhaps do interactive lessons that can be found on some websites. This article will focus on teaching algebra for dummies. We will provide you with the things you need to consider in order to learn algebra. Algebra for Dummies Tip One In order to learn algebra you need to start with the basics. Therefore, you need to start with the easiest form and learn and understand by heart. Do all the equations that is related to the fundamental or the most basic of the algebraic equations and master it. once you are done with mastering the basics you can now go ahead and level up to a bit more complicated issue, once again you just to master this again and fully understand its applications after this you can now then repeat the process until you the most advanced and complicated concepts. This can prove to be very effective rather than dipping yourself with a bit of everything without completely immersing your mind and thus having very little understanding of the different algebraic concepts. Algebra for Dummies Tip Two Algebra can be mastered with a very simple equation. Algebra = Practice. This is definitely true, in order to fully master and understand very complicated concepts of algebra, one must experience algebra again and again until the understanding of the different algebraic equations become second nature to him and he can then easily respond without forcing the persons brain, as it would naturally once the person sees the equation. A very effective to learn this is through writing the equations you want to learn on sheets of paper. Youve got to make sure that you write only one equation in one sheet. You the sheets youve written to practice the specific equation you wrote on the paper. Continue doing this and this can have great effects for you. Algebra for Dummies Tip Three Dont be in a hurry when trying to learn algebra, because if there are undeniable facts when learning this it would not being able to learn it overnight. Therefore, dont put too much pressure on yourself, and as much as possible relax and be at ease when dealing with the equations. Stressing your brain wont give answers, it would just make it a lot harder to think and understand what is really in front of you. Algebra for Dummies Tip Four If you want to be a good soldier, you need to have a good weapon. Therefore arm yourself with the best learning resources you can find. There are thousands of books about algebra, however there are very few that aims to explain it in a manner that is easy to understand, therefore you have to research and find the best book that would your mode thinking and become an effective tool to learn the subject. You may also join community forums where you find tips and ask for help in your struggles. The concepts of math are seen to be difficult to comprehend; many regards math as a subject to the extremely gifted minds. This is overstated learning math is not as complex as people have made it to be. Algebra happens to be a part of math that is needed in every part of life; decision making and effective reasoning are based on the concepts of algebra. As an algebra tutor, when your students begin to ask about the importance of algebra in life, it is a sign they are not getting the best out of the class. You need to assess the way you take the class either the students are paranoid or they find the class boring. Once you figure out what the problem is, it is your responsibility as a tutor to fix the problem. You can ask them to buy a particular algebra for dummies book, and practice with them to aid their learning. Math is required in every part of life, to survive in this ever changing society; your knowledge of basic math is extremely useful. Math is required to control expenses and budgets, and to help you with your decisions. Sometimes, algebra problems come as real life problems; students see themselves in such situations and apply their math skills to solve such problems. Basically, as math is essential, so is algebra the aspect of math that comprises of symbols and the basic math rules that manage their operations. Algebra defines the procedures required to solve complicated math problems, though many find it difficult; it can also be very easy, depending on your knowledge. People exaggerate its complexity because they are not willing to dedicate their time in learning. If you are determined to learn how to do algebra, there are numerous tools algebra worksheets available online you can use to aid your learning. Work with different books (any algebra for dummies book), you will be provided with lots of exercises to work with. This eliminates the fear you have towards algebra and increases your learning curve. But it is advised to learn basic math skills before learning algebra; lots of pre algebra for dummies textbooks are available that will guide you with the long division, and multiplications, the additions and subtractions. After which you can lay your hands on any algebra for dummies books. You dont have to memorize or cram the steps involved; the book will walk you through any obstacle you might be faced with. All the reasons behind each concept are explained thoroughly and accurately. You will learn different classifications of numbers, fractions and decimals, radicals and exponents and how to solve quadratic and linear equations. You will learn how to use graphs in solving equations, and importantly means of solving word or real life problems. Learning algebra can be fun once you work with the right book any algebra for dummies book will be extremely valuable. It takes you literarily by the hand to shows you ways of solving algebra problems. You dont need to cram your way to success in class, once you understand the basics of algebra; you will realize how easy it is. Get yourself any college algebra dummies book to understand algebra once and for all. Algebra seems complex and overbearing on many, but can be fun when done right. Lots of students find its concept difficult to comprehend they hate the algebra class. It is down to their algebra tutor to understand their frustration at the subject and do everything necessary to reaffirm their belief. There are two ways a tutor can do this; allowing the students to use proven algebra books (any algebra for dummies books will do) or increasing their learning by incorporating algebra games into the class. One option that is quite affordable is the use of quality algebra books to aid the students learning. Quadratic and linear equations and graphs are concepts that students find challenging, but are important in their adequate understanding of math. Therefore it is always a good idea for their parents to assist them with any college algebra dummies books so as to help them know how to do algebra. Learning the basics of algebra requires adequate understanding of the core math concepts long division and multiplication and others are necessary. If you find difficulty with these, you need to learn pre algebra concepts before going on to learn how to do algebra. Pre algebra for dummies is useful, if you are just starting out. This article is written to talk about a simple and effective way to solve two or more linear algebraic equations involving two variables (x and y variables). The only way to do this is manipulating the equations so as to find a pattern. Substitution method (substituting one value of a variable in one equation into the other) is the simplest means of solving such algebraic equations. Carrying this out requires you to look for the common property shared amongst all the equations. This is achieved after lots of practice; you need to practice different forms of linear algebraic equations to master how to find solutions. Make use of algebra for dummies, or talk to your teacher, he/she will guide you. For example, when you are given an equation like 6x 3y = 0, and y x = 1. It is easy to find the value of y in the 2nd equation; y = 1+x, to find the other value, all you need is to substitute this value into the 1st equation, 6x 3(1+x) = 0. As you can see, we have eliminated the y terms from the 1st equation. Solving for the value of x gives 6x 3x = 3, which yields x = 1. Plug this value into any equation and the value of y can be found (using the 2nd equation, y = 2). This method gives the accurate means of solving a system of linear algebraic equation, this example is quite simple, for tougher ones, consult your algebra textbooks. There are other means of solving two or more linear equations; any college algebra dummies book will be helpful. If you hit the brick wall, talk to your algebra tutor, he/she will tell you what to do. Therefore start learning how to do algebra by consulting any college algebra dummies book, you will be provided with a host of means of solving different forms of algebra equations.
677.169
1
This unit consists of two computer programs. The first teaches X,Y plotting; the second is a demonstration of coordinate transformations, matrices, vector equations of lines and perspective and will draw a picture of... High school or college students taking an introductory trigonometry course may find this site useful. Three modules comprise the site, and each provides an overview of basic concepts. Some of the most common...
677.169
1
Thinking Mathematically, Fifth Edition Average rating 3.7 out of 5 Based on 127 Ratings and 105 Reviews Book Description pr... More provides helpful tools in every chapter to help them master the material. Voice balloons are strategically placed throughout the book, showing what an instructor would say when leading a student through a problem. Study tips, chapter review grids, Chapter Tests, and abundant exercises provide ample review and practice.
677.169
1
365 total 5 944 4 273 3 73 2 45 1 30 Problems Doesn't recognize hyperbolic functions and will not produce indefinite integrals. It would also be nice if the taylor series option would show the expansion instead of giving just the numerical result Problems Doesn't recognize hyperbolic functions and will not produce indefinite integrals. It would also be nice if the taylor series option would show the expansion instead of giving just the numerical result musicThis app can help update firmware when someone uses this app has been updated. First device get update. Your device get it with. In update system feature. This app help get update package file and install by recovery mode. (like OTA or manual update by sideload method) You can be sure that it is safe. If you find any problems in recovery mode can be viewed by pressing the Volume up button. Followed by the power button. If you not understand you can email inquiries please do not ask for trouble by writing a comment in the app.Basics: -Enter values and view results as you would write them -Swipe up, down, left, or right to quickly switch between keyboard pages. -Long click on keyboard key to bring up dialog about key. -Undo and Redo keys to easily fix mistakes. -Cut, Copy, and Paste. -User defined functions with f, g, h Graphing: -Graph three equations at once. -View equations on graph or in table format. -Normal functions such as y=x^2 -Inverse functions such as x=y^2 -Circles such as y^2+x^2=1 -Ellipses, Hyperbola, Conic Sections. -Inequalities -Logarithmic scaling -Add markers to graph to view value at given point. -View delta and distance readings between markers on graph. -View roots and intercepts of traces on graph. Q. Is there are tutorial anywhere explaining how to use the graphing calculator? A. There are three into tutorials in the app for the calculator, graph equations, and graph screens. Additional tutorials can be found on our website Q. How do I get to the keys for pi, e, solve, etc? A. There are four keyboard pages. Each swipe direction across the keyboard moves you to a different page. The default page is the swipe down page. To get to the page with trig functions, swipe left. To get to the matrix keys, swipe up. To get to the last page, swipe right. No matter what page you are on, the swipe direction to move to a specific page is always the same. Q. What do you have planned for future releases? A. You can keep up to date on the latest news on our blog at . This news will include what is coming up in future releases. Also feel free to leave comments and let me know what you think!Tips: -sto() function may be used for infinite series/mathematical induction, Newton's Method, etc. Notes: -When tracing functions with fractional powers, tangent line is reversed for negative x-values. -Odd-numbered roots with real solutions are evaluated as a real number (e.g.: (-8)^(1/3) = -2), unlike other calculators, and computer algebra systems such as Wolfram. Grapher is useful application for all pupils and students. Ease interface will help you to build any graph or function on Cartesian coordinate system in few seconds. You can drow simple,parametric or polar type of function. You can build a lot of functions in one time on same screen in different colors. Description Calculator Plus is an advanced, modern and easy to use scientific calculator #1. Calculator Plus helps you to do basic and advanced calculations on your mobile device. IMPORT * easy to use * home screen widget * no need to press equals button any more - the result is calculated automatically * smart cursor positioning * copy/paste in one button * landscape/portrait orientations * drag buttons up or down to use special functions, operators etc * modern interface with possibility to choose themes * highlighting of expressions * history with all previous calculations and undo/redo buttons * variables and constants support (build-in and user defined) * complex number computations * support for a huge variety of functions * expression simplification: use 'identical to' sign (≡) to simplify current expression (2/3+5/9≡11/9, √(8)≡2√(2)) Why Calculator plus needs INTERNET permission? Currently application needs such permission only for one purpose - to show ads. How can I use functions written in the top right and bottom right corners of the button? Push the button and slide lightly up or down. Depending on value showed on the button action will occur. How can I toggle between radians and degrees? To Examples: 268° = 4.67748 30.21° = 0.52726 rad(30, 21, 0) = 0.52726 deg(4.67748) = 268 Does Calculator Plus support %? Yes, % function can be found in the top right corner of / button. Examples: 100 + 50% = 150 100 * 50% = 50 100 + 100 * 50% * 50% = 125 100 + (100 * 50% * (25 + 25)% + 100%) = 150 Note: 100 + (20 + 20)% = 140, but 100+ (20% + 20%) = 124.0 100 + 50% ^ 2 = 2600, but 100 + 50 ^ 2% = 101.08 Does Calculator Plus support fractional calculations? Yes, you can type your fractional expression in the editor and use ≡ (in the top right corner of = button). Also you can use ≡ to simplify expression. Examples: 2/3 + 5/9 ≡ 11/9 2/9 + 3/123 ≡ 91/369 (6-t) ^ 3 ≡ 216 - 108t + 18t ^ 2 - t ^ 3 Does C++ support complex calculations? Yes, just enter complex expression (using i or √(-1) as imaginary number). ONLY IN RAD MODE! Examples: (2i + 1) ^ = -3 + 4i e ^ i = 0.5403 + 0.84147i Can C++ plot graph of the function? Yes, type expression which contains 1 undefined variable (e.g. cos(t)) and click on the result. In the context menu choose 'Plot graph'.
677.169
1
The American Mathematical Association of Two-Year Colleges (AMATYC) has compiled a collection of mathematics resources related to various subjects and disciplines. ?Math Across the Community College Curriculum? is the... This Office Administration course was created by a team of educators at Florida Community College at Jacksonville to combine business and math. In-depth lessons are provided that address mathematics in consumer finance... A collection of games and puzzles for math review, this page provides visitors with a number of ways to engage in math topics. There are ten java-based and eleven non-java flashcard collections on concepts including... Produced by Science Academy Software, this site is a collection of math questions on subjects including basic arithmetic, order of operations, calculating perimeters and distance, exponents, and bar graphs. It is an...
677.169
1
Writing A Calculus I (Math 151) Project 1. Objective: To learn how Calculus is linked to your chosen major or field. 2. Guidelines: a. You may choose up to three classmates to form a group. b. You need to identify a real-life problem in your fields that you would like to do. (For example, it could be an optimization problem.) c. You need to use technological tools to demonstrate how you use Calculus to achieve your answer. 3. Writing up your report: You need to prepare a Word or PowerPoint file 4. Oral presentation: December 10.
677.169
1
Invigorate instruction and engage students with this treasure trove of "Great Ideas" compiled by two of the greatest minds in mathematics. From commonly taught topics in algebra, geometry, trigonometry, and statistics, to more advanced explorations into indirect proofs, binomial theorem, irrationality, relativity, and more, this guide outlines concepts and techniques that will i...show morenspire veteran and new educators alike. This updated second edition offers more proven practices for bringing math concepts to life in the classroom, including: 114 innovative strategies organized by subject area User-friendly content identifying "objective," "materials," and "procedure" for each technique A range of teaching models, including hands-on and computer-based methods Specific and straightforward examples with step-by-step lessons Written by two distinguished leaders in the field-mathematician, author, professor, university dean, and popular commentator Alfred S. Posamentier, along with mathematical pioneer and Nobel Prize recipient Herbert A. Hauptman-this guide brings a refreshing perspective to secondary math instruction to spark renewed interest and success among students and teachers
677.169
1
With the present development of the computer technology, it is necessary to develop efficient algorithms for solving problems in science, engineering and technology. This course gives a complete procedure for solving different kinds of problems occur in engineering numerically. OBJECTIVES At the end of the course, the students would be acquainted with the basic concepts in numerical methods and their uses are summarized as follows: i. The roots of nonlinear (algebraic or transcendental) equations, solutions of large system of linear equations and eigen value problem of a matrix can be obtained numerically where analytical methods fail to give solution. ii. When huge amounts of experimental data are involved, the methods discussed on interpolation will be useful in constructing approximate polynomial to represent the data and to find the intermediate values.
677.169
1
Algebraic Videogame Programming Bootstrap is a curricular module for students ages 12-16, which teaches algebraic and geometric concepts through computer programming. At the end of the module, students have a completed workbook filled with word problems, notes and math challenges, as well as a videogame of their own design, which they can share with friends and family. Our one-page overview summarizes our approach and its connection to algebra. We work with schools, districts and tech-educational programs across the country, helping teachers reach thousands of students each year. Bootstrap has been used in both math and technology classes, often by teachers with limited prior experience teaching computing. We believe strongly in high-quality professional development, and our hands-on teacher-training workshops cover both content and pedagogic techniques for delivering Bootstrap effectively. For Math Teachers Bootstrap also builds in a pedagogical approach to solving Word Problems called the Design Recipe. Students solve word problems to make a rocket fly (linear equations), respond to keypresses (piecewise functions) or explode when it hits a meteor (distance formula). In fact, this same technique has been successfully used at the university level for decades. For CS Teachers Knowing how to write code is good, but it doesn't make you a programmer. In addition to learning a full-strength programming language, Bootstrap teaches solid program design skills, such as stating input and types, writing test cases, and explaining code to others. After Bootstrap, these skills can be put to use in other programming languages, letting students build on what they've learned. A Note for Parents Before algebra, your child's math homework was all about computing an answer, by adding, subtracting, solving, etc. Once Algebra introduces functions, however, everything changes. Rather than "solving for x", they'll be asked to think about whether a function f(x) is linear, how many roots it has, etc. The jump from "getting the answer" to "describing a function" is challenging for students, as it requires them to think more abstractly than ever before. Algebra isn't just harder — it's completely different. Unlike Python, Scratch or Javascript, functions and variables behave exactly the same way in Bootstrap that they do in your child's math book. Bootstrap focuses on order of operations, the Cartesian plane, function composition and definition, solving word problems and more. Instead of using the Pythagorean Theorem to calculate the heights of ladders leaning against walls, students use the same class time to determine the distance between characters in their game and make them collide. By shifting classwork from abstract pencil-and-paper problems to a series of relevant programming problems, Bootstrap demonstrates how algebra applies in the real world, using an exciting, hands-on project. "" — Our team Bootstrap is a joint partnership between Emmanuel Schanzer (a computer scientist and former teacher, now at the Harvard Graduate School of Education), Kathi Fisler (WPI), and Shriram Krishnamurthi (Brown University). Emma Youndtsmith is our regional manager in the Northeast. Together, we build curricula, software, and professional development for teachers across the country. Bootstrap builds on the pioneering work of Program By Design by Matthias Felleisen and his collaborators. Our Supporters We would like to thank the following, for their volunteer and financial support over the years: Apple, Cisco, the Entertainment Software Association (ESA), Facebook, Google, as well as the Google Inc. Charitable Giving Fund of Tides Foundation, IBM, Jane Street Capital, LinkedIn, Microsoft, The National Science Foundation, NVIDIA, Thomson/Reuters, TripAdvisor and the generous individuals who have given us private donations. If you would like to support Bootstrap with a donation, send a check made out to Brown University to our PI, Shriram Krishnamurthi, at his mailing address. Be sure to include this letter, indicating that you wish for the funds to be put towards Bootstrap. Once your check is received, we'll send you a receipt for your tax records.
677.169
1
Questions and Comments Everybody uses math whether they realize it or not. Like reading and writing, a solid understanding of mathematics is essential for everyday living and in the workplace. Mathematical skills help us to shop wisely, buy the right insurance, remodel a home, interpret statistics, understand population growth, calculate travel distances and so much more. Through mathematics we develop numeracy, reasoning, thinking and problem solving skills. These skills are valued not only in science, business, trades and technology, but in other areas like fine arts, music and sports. More than ever, Alberta students need a strong grounding in mathematics to meet the challenges of the 21st century and to be successful in their futures. Alberta's revised mathematics program Alberta is recognized worldwide as a leader in the development of quality curriculum. The revised Kindergarten to Grade 12 mathematics program maintains this standard by integrating current research, developments and trends in mathematics learning and teaching. The revised mathematics programs of study were developed in collaboration with teachers, administrators, parents, business representatives, post-secondary institutions and others to ensure they meet the needs of Alberta students. Alberta Education began to roll out the revised mathematics curriculum, province-wide, through a staggered implementation schedule to ease the transition on students, teachers and school jurisdictions as well publishers who provide learning resources. The revised program was approved by the Minister of Education in April 2007 for implementation according to the following schedule: Year 2008 2009 2010 2011 2012 Grade(s) K, 1, 4, 7 2, 5, 8 3, 6, 9,10 11 12 Finding information about mathematics We have organized our web pages into three groups, students, parents and educators, with relevant information about the revised mathematics curriculum that we hope you find useful.
677.169
1
Synopses & Reviews Publisher Comments: This first volume of strategic activities is designed to develop through a hands-on approach, a basic mathematical understanding and appreciation of fractals. The concepts presented on fractals include self-similarity, the chaos game, and complexity as it relates to fractal dimension. These strategic activities have been developed from a sound instructional base, stressing the connections to the contemporary curriculums recommended in the National Council of Teachers of Mathematics' Curriculum and Evaluation Standards for School Mathematics. Where appropriate the activities take advantage of the technological power of the graphics calculator. These activites make excellent extensions to many of the topics that are already taught in the current curriculum. Together, they can be used as a complete unit or as the beginning for a semester course on fractals. Book News Annotation: This first volume of strategic classroom activities (volume 2 is reviewed in the June 1992 SciTech Book News) is designed to develop, through a hands-on approach, a basic mathematical understanding and appreciation of fractals. The concepts presented include self-similarity, the chaos game, and complexity as it relates to fractal dimension. The slide package that accompanies the volume includes some of the highest quality fractal images available
677.169
1
Welcome to 2014! We have successfully navigated the holidays, and I look forward to a couple of months of sustained learning and academic growth. I'm sure the students feel the same way! Seventh graders have recently completed a unit in which they learned to us rules of algebra to solve linear equations methodically. They have now begun the study of linear functions, utilizing the skills they learned and applying them to equations that have two unknown quantities. Students will also be showing representations of these equations with tables and graphs and use them to make estimations and predictions. Eighth graders have just completed a second unit involving linear functions. In this unit, students went deeper into problem solving, using algebraic formulas to create equations that could be used solve the problems. For our next unit, the third involving linear functions, eighth graders will learn strategies to solve linear systems. Linear systems are problems that involve more than one equation. Examples of these include mixture problems and complex distance/rate problems. A typical linear system problem is as follows: Two vans are headed to Marine World loaded with kids. Van 1 leaves at 8:00 a.m., traveling at 65 mph, and expects to arrive at Marine World at 9:45 a.m. Van 2 is delayed 10 minutes when one of the passengers discovers he forgot his lunch money. How fast will Van 2 need to drive in order to arrive at the same time as Van 1? Students will be solve these problems by drawing diagrams, using formulas and graphing. If you have any questions about my grading policy, homework expectations or any other aspect of 7/8 Math, please do not hesitate to call (652-2635 x119) or send an email. If meetings are more favorable to you, I can generally meet after school on any day but Mondays (schedule permitting) to talk about the math program. mp3 file: This is an audio file and can be opened with an audio player or editor such as QuickTime. Download the free QuickTime Player for PC or Macintosh
677.169
1
Workbook provides the targeted training students need to bring their math skills up to speed including: An overview of the material covered on the Math sections of the GMAT and GRE A comprehensive review of the math on the test, including arithmetic, algebra, word problems and geometry Exercises designed to help readers assess their current skill level and focus study efforts Related Subjects Read an Excerpt Introduction to Graduate Math chapter one Been there, done that. If you're considering applying to graduate school or business school, then you've already seen all the math you need for both the GRE and the GMAT. You would have covered the relevant math content in junior high. In fact, the math that appears on the GRE and GMAT is almost identical to the math tested On the SAT or ACT. You don't need to know trigonometry You don't need to know calculus. No surprises -- it's all material you've seen before. The only problem is, you may not have seen it lately. When was the last time you had to add a bunch of fractions without a calculator? No matter how much your memories of junior high algebra classes have dimmed, don't panic. The GRE and the GMAT test a limited number of core math concepts in predictable ways. Certain topics come up in every test, and, chances are, these topics will be expressed in much the same way; even Some of the words and phrases appearing in the questions are predictable. Since the tests are so formulaic, we can show you the math you're bound to encounter. Some practice on testlike questions, such as those in the following chapters, will ready you for the questions you will see on the actual test. Here is a checklist of core math concepts you'll need for the GRE and GMAT. These concepts are vital, not only because they are tested directly on every GRE and GMAT, but also because you need to know how to perform these simpler operations in order to perform more complicated tasks. For instance, you won't be able to find the volume of a cylinder if you can't find the area of a circle. We know the mathoperations on the following list are pretty basic, but make sure you know how to do them. The GMAT will give you a scaled quantitative score from 0 to 60. (The average score is 30.) This score reflects your performance on the math portion of the test compared to all other GMAT test takers. You will also receive an overall score that reflects your performance on both the math and the verbal portions of the test. This is a scaled score from 200 to 800. HOW MATH IS SCORED ON THE GRE The GRE will give you a scaled quantitative score from 200 to 800. (The average score is 500.) This score reflects your performance on the math portion of the GRE compared to all other GRE test t
677.169
1
Publisher's Description Geometry Master covers the essential concepts of geometry including 3D solids, 2D shapes, polygons, formulas, and proofs. We know that geometry is difficult for many students because of proofs, which is why our software provides several options to help you learn proofs by helping you memorize the basic postulates and theorems, asking you to prove triangular relationships, and showing you why proofs provide information the way they do to help you master proofs. Our software breaks proofs down to their parts and asks you questions to help you understand why each part of a proof is done a certain way. Our software features: Over 1000 problems designed to test your knowledge of geometry, especially proofs and triangular relationships. Time trials feature lets you take exams using a timer to help you pass those quizzes and exams where time is an issue. Practice lets you practice answering questions and see the results immediately. Test lets you answer questions and see the results when the test is over. Drill lets you memorize important topics and concepts. The number of questions can be set from 1 to 100 and the number of minutes can be set from 1 to 200. A calculator is provided to help you perform calculations. A working area which can be used as scratch paper is also provided. What's new in this version: Changed how settings will be saved and loaded
677.169
1
Math Welcome to the Math Department! The mathematics curriculum is designed to provide a rigorous foundation in the basics of mathematics and the tools to foster logical thought and analysis. Critical thinking, collaboration and mathematical modeling are emphasized at all levels. In all mathematics courses, faculty help students develop successful study skills and effective test-preparation techniques. For students whose backgrounds and aptitudes are strong, there are advanced sections of courses in our core curriculum. These include A.P. Calculus BC, Multivariable Calculus with Differential Equations, Advanced Math/Science Research, and A.P. Computer Science. Each of these courses allow students who are passionate about mathematics to pursue excellence in the subject at the highest level. We also offer an Advanced Math Science Research Program for qualified students. Click here to see more about this innovative program and what it has to offer.
677.169
1