20,99 €
Plot graphs, solve equations, and write code in a flash! If you work in a STEM field, chances are you'll be using MATLAB on a daily basis. MATLAB is a popular and powerful computational tool and this book provides everything you need to start manipulating and plotting your data. MATLAB has rapidly become the premier data tool, and MATLAB For Dummies is a comprehensive guide to the fundamentals. MATLAB For Dummies guides you through this complex computational language from installation to visualization to automation. * Learn MATLAB's language fundamentals including syntax, operators, and data types * Understand how to use the most important window in MATLAB - the Command Window * Get the basics of linear algebra to get up and running with vectors, matrices, and hyperspace * Automate your work with programming scripts and functions * Plot graphs in 2D and 3D to visualize your data * Includes a handy guide for MATLAB's functions and plotting routines MATLAB is an essential part of the analysis arsenal and MATLAB For Dummies provides clear, thorough guidance to get the most out of your data.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 503
MATLAB® For Dummies®
Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com
Copyright © 2015 by John Wiley & Sons, Inc., Hoboken, New Jersey
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the Publisher. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Trademarks: Wiley, For Dummies, the Dummies Man logo, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and may not be used without written permission. MATLAB is a registered trademark of Mathworks, Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit www.wiley.com/techsupport.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2014940494
ISBN: 978-1-118-82010-0 (pbk); ISBN 978-1-118-82003-2 (ebk); ISBN 978-1-118-82434-4 (ebk)
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
Table of Contents
Introduction
About This Book
Foolish Assumptions
Icons Used in This Book
Beyond the Book
Where to Go from Here
Part I: Getting Started With MATLAB
Chapter 1: Introducing MATLAB and Its Many Uses
Putting MATLAB in Its Place
Understanding how MATLAB relates to a Turing machine
Using MATLAB as more than a calculator
Determining why you need MATLAB
Discovering Who Uses MATLAB for Real-World Tasks
Knowing How to Get the Most from MATLAB
Getting the basic computer skills
Defining the math requirements
Applying what you know about other procedural languages
Understanding how this book will help you
Getting Over the Learning Curve
Chapter 2: Starting Your Copy of MATLAB
Installing MATLAB
Discovering which platforms MATLAB supports
Getting your copy of MATLAB
Performing the installation
Activating the product
Meeting the MATLAB Interface
Starting MATLAB for the first time
Employing the Command window
Using the Current Folder toolbar
Viewing the Current Folder window
Changing the MATLAB layout
Chapter 3: Interacting with MATLAB
Using MATLAB as a Calculator
Entering information at the prompt
Entering a formula
Copying and pasting formulas
Changing the Command window formatting
Suppressing Command window output
Understanding the MATLAB Math Syntax
Adding, subtracting, multiplying, and dividing
Working with exponents
Organizing Your Storage Locker
Using ans — the default storage locker
Creating your own storage lockers
Operating MATLAB as More Than a Calculator
Learning the truth
Using the built-in functions
Accessing the function browser
Recovering from Mistakes
Understanding the MATLAB error messages
Stopping MATLAB when it hangs
Getting Help
Exploring the documentation
Working through the examples
Relying on peer support
Obtaining training
Requesting support from MathWorks
Contacting the authors
Chapter 4: Starting, Storing, and Saving MATLAB Files
Examining MATLAB’s File Structure
Understanding the MATLAB files and what they do
Exploring folders with the GUI
Exploring folders with commands
Working with files in MATLAB
Accessing and Sharing MATLAB Files
Opening
Importing
Exporting
Saving Your Work
Saving variables with the GUI
Saving variables using commands
Saving commands with the GUI
Saving commands using commands
Part II: Manipulating and Plotting Data in MATLAB
Chapter 5: Embracing Vectors, Matrices, and Higher Dimensions
Working with Vectors and Matrices
Understanding MATLAB’s perspective of linear algebra
Entering data
Adding and Subtracting
Understanding the Many Ways to Multiply and Divide
Performing scalar multiplication and division
Employing matrix multiplication
Effecting matrix division
Creating powers of matrices
Working element by element
Using complex numbers
Working with exponents
Working with Higher Dimensions
Creating a multidimensional matrix
Accessing a multidimensional matrix
Replacing individual elements
Replacing a range of elements
Modifying the matrix size
Using cell arrays and structures
Using the Matrix Helps
Chapter 6: Understanding Plotting Basics
Considering Plots
Understanding what you can do with plots
Comparing MATLAB plots to spreadsheet graphs
Creating a plot using commands
Creating a plot using the Workspace window
Creating a plot using the Plots tab options
Using the Plot Function
Working with line color, markers, and line style
Creating multiple plots in a single command
Modifying Any Plot
Making simple changes
Adding to a plot
Deleting a plot
Working with subplots
Plotting with 2D Information
Chapter 7: Using Advanced Plotting Features
Plotting with 3D Information
Using the bar() function to obtain a flat 3D plot
Using bar3() to obtain a dimensional 3D plot
Using barh() and more
Enhancing Your Plots
Getting an axes handle
Modifying axes labels
Adding a title
Rotating label text
Employing annotations
Printing your plot
Part III: Streamlining MATLAB
Chapter 8: Automating Your Work
Understanding What Scripts Do
Creating less work for yourself
Defining when to use a script
Creating a Script
Writing your first script
Using commands for user input
Copying and pasting into a script
Converting the Command History into a script
Continuing long strings
Adding comments to your script
Revising Scripts
Calling Scripts
Improving Script Performance
Analyzing Scripts for Errors
Chapter 9: Expanding MATLAB’s Power with Functions
Working with Built-in Functions
Learning about built-in functions
Sending data in and getting data out
Creating a Function
Understanding script and function differences
Understanding built-in function and custom function differences
Writing your first function
Using the new function
Passing data in
Passing data out
Creating and using global variables
Using subfunctions
Nesting functions
Using Other Types of Functions
Inline functions
Anonymous functions
Chapter 10: Adding Structure to Your Scripts
Making Decisions
Using the if statement
Using the switch statement
Understanding the switch difference
Deciding between if and switch
Creating Recursive Functions
Performing Tasks Repetitively
Using the for statement
Using the while statement
Ending processing using break
Ending processing using return
Determining which loop to use
Creating Menus
Part IV: Employing Advanced MATLAB Techniques
Chapter 11: Importing and Exporting Data
Importing Data
Performing import basics
Importing mixed strings and numbers
Defining the delimiter types
Importing selected rows or columns
Exporting Data
Performing export basics
Exporting scripts and functions
Working with Images
Exporting images
Importing images
Chapter 12: Printing and Publishing Your Work
Using Commands to Format Text
Modifying font appearance
Using special characters
Adding math symbols
Publishing Your MATLAB Data
Performing advanced script and function publishing tasks
Saving your figures to disk
Printing Your Work
Configuring the output page
Printing the data
Chapter 13: Recovering from Mistakes
Working with Error Messages
Responding to error messages
Understanding the MException class
Creating error and warning messages
Setting warning message modes
Understanding Quick Alerts
Relying on Common Fixes for MATLAB’s Error Messages
Making Your Own Error Messages
Developing the custom error message
Creating useful error messages
Using Good Coding Practices
Part V: Specific MATLAB Applications
Chapter 14: Solving Equations and Finding Roots
Working with the Symbolic Math Toolbox
Obtaining your copy of the Toolbox
Installing the Symbolic Math Toolbox
Working with the GUI
Typing a simple command in the Command window
Performing Algebraic Tasks
Differentiating between numeric and symbolic algebra
Solving quadratic equations
Working with cubic and other nonlinear equations
Understanding interpolation
Working with Statistics
Understanding descriptive statistics
Understanding robust statistics
Employing least squares fit
Chapter 15: Performing Analysis
Using Linear Algebra
Working with determinants
Performing reduction
Using eigenvalues
Understanding factorization
Employing Calculus
Working with differential calculus
Using integral calculus
Working with multivariate calculus
Solving Differential Equations
Using the numerical approach
Using the symbolic approach
Chapter 16: Creating Super Plots
Understanding What Defines a Super Plot
Using the Plot Extras
Using grid()
Obtaining the current axis using gca
Creating axis dates using datetick()
Creating plots with colorbar()
Interacting with daspect
Interacting with pbaspect
Working with Plot Routines
Finding data deviations using errorbar()
Ranking related measures using pareto()
Plotting digital data using stairs()
Showing data distribution using stem()
Drawing images using fill
Displaying velocity vectors using quiver()
Displaying velocity vectors using feather()
Displaying velocity vectors using compass()
Working with polar coordinates using polar()
Displaying angle distribution using rose()
Spotting sparcity patterns using spy()
Employing Animation
Working with movies
Working with objects
Performing data updates
Part VI: The Part of Tens
Chapter 17: Top Ten Uses of MATLAB
Engineering New Solutions
Getting an Education
Working with Linear Algebra
Performing Numerical Analysis
Getting Involved in Science
Engaging Mathematics
Exploring Research
Walking through a Simulation
Employing Image Processing
Embracing Programming Using Computer Science
Chapter 18: Ten Ways to Make a Living Using MATLAB
Working with Green Technology
Looking for Unexploded Ordinance
Creating Speech Recognition Software
Getting Disease under Control
Becoming a Computer Chip Designer
Keeping the Trucks Rolling
Creating the Next Generation of Products
Designing Equipment Used in the Field
Performing Family Planning
Reducing Risks Using Simulation
Appendix A: MATLAB Functions
Appendix B: MATLAB’s Plotting Routines
About the Authors
Cheat Sheet
More Dummies Products
Table of Contents
Begin Reading
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
351
352
353
354
355
356
357
358
359
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
377
378
379
380
381
382
383
407
409
411
412
MATLAB is an amazing product that helps you perform math-related tasks of all sorts using the same techniques that you’d use if you were performing the task manually (using pencil and paper, slide rule, or abacus if necessary, but more commonly using a calculator). However, MATLAB makes it possible to perform these tasks at a speed that only a computer can provide. In addition, using MATLAB reduces errors, streamlines many tasks, and makes you more efficient. However, MATLAB is also a big product that has a large number of tools and a significant number of features that you might never have used in the past. For example, instead of simply working with numbers, you now have the ability to plot them in a variety of ways that help you better communicate the significance of your data to other people. In order to get the most from MATLAB, you really need a book like MATLAB For Dummies.
The main purpose of MATLAB For Dummies is to reduce the learning curve that is a natural part of using a product that offers as much as MATLAB does. When you first start MATLAB, you might become instantly overwhelmed by everything you see. This book helps you get past that stage and become productive quickly so that you can get back to performing amazing feats of math wizardry.
In addition, this book is designed to introduce you to techniques that you might not know about or even consider because you haven’t been exposed to them before. For example, MATLAB provides a rich plotting environment that not only helps you communicate better, but also makes it possible to present numeric information in a manner that helps others see your perspective. Using scripts and functions will also reduce the work you do even further and this book shows you how to create custom code that you can use to customize the environment to meet your specific needs.
After you’ve successfully installed MATLAB on whatever computer platform you’re using, you start with the basics and work your way up. By the time you finish working through the examples in this book, you’ll be able to perform a range of simple tasks in MATLAB that includes writing scripts, writing functions, creating plots, and performing advanced equation solving. No, you won’t be an expert, but you will be able to use MATLAB to meet specific needs in the job environment.
To make absorbing the concepts even easier, this book uses the following conventions:
Text that you’re meant to type just as it appears in the book is bold. The exception is when you’re working through a step list: Because each step is bold, the text to type is not bold.When you see words in italics as part of a typing sequence, you need to replace that value with something that works for you. For example, if you see “Type Your Name and press Enter,” you need to replace Your Name with your actual name.Web addresses and programming code appear in monofont. If you’re reading a digital version of this book on a device connected to the Internet, note that you can click the web address to visit that website, like this: http://www.dummies.com.When you need to type command sequences, you see them separated by a special arrow like this: File⇒New File. In this case, you go to the File menu first and then select the New File entry on that menu. The result is that you see a new file created.You might find it difficult to believe that we’ve assumed anything about you — after all, we haven’t even met you yet! Although most assumptions are indeed foolish, we made these assumptions to provide a starting point for the book.
It’s important that you’re familiar with the platform you want to use because the book doesn’t provide any guidance in this regard. (Chapter 2 does provide MATLAB installation instructions.) To provide you with maximum information about MATLAB, this book doesn’t discuss any platform-specific issues. You really do need to know how to install applications, use applications, and generally work with your chosen platform before you begin working with this book.
This book isn’t a math primer. Yes, you see lots of examples of complex math, but the emphasis is on helping you use MATLAB to perform math tasks rather than learn math theory. Chapter 1 provides you with a better understanding of precisely what you need to know from a math perspective in order to use this book successfully.
This book also assumes that you can access items on the Internet. Sprinkled throughout are numerous references to online material that will enhance your learning experience. However, these added sources are useful only if you actually find and use them.
As you read this book, you see icons in the margins that indicate material of interest (or not, as the case may be).This section briefly describes each icon in this book.
Tips are nice because they help you save time or perform some task without a lot of extra work. The tips in this book are timesaving techniques or pointers to resources that you should try in order to get the maximum benefit from MATLAB.
We don’t want to sound like angry parents or some kind of maniac, but you should avoid doing anything that’s marked with a Warning icon. Otherwise, you might find that your application fails to work as expected, you get incorrect answers from seemingly bulletproof equations, or (in the worst-case scenario) you lose data.
Whenever you see this icon, think advanced tip or technique. You might find these tidbits of useful information just too boring for words, or they could contain the solution you need to get a program running. Skip these bits of information whenever you like.
If you don’t get anything else out of a particular chapter or section, remember the material marked by this icon. This text usually contains an essential process or a bit of information that you must know to work with MATLAB successfully.
This book isn’t the end of your MATLAB experience — it’s really just the beginning. We provide online content to make this book more flexible and better able to meet your needs. That way, as we receive email from you, we can address questions and tell you how updates to either MATLAB or its associated add-ons affect book content. In fact, you gain access to all these cool additions:
Cheat sheet: You remember using crib notes in school to make a better mark on a test, don’t you? You do? Well, a cheat sheet is sort of like that. It provides you with some special notes about tasks that you can do with MATLAB that not every other person knows. You can find the cheat sheet for this book at http://www.dummies.com/cheatsheet/matlab. It contains really neat information such as the keyboard shortcuts that you use most often to speed MATLAB use.Dummies.com online articles: A lot of readers were skipping past the parts pages in For Dummies books, so the publisher decided to remedy that. You now have a really good reason to read the parts pages — online content. Every parts page has an article associated with it that provides additional interesting information that wouldn’t fit in the book. You can find the articles for this book at http://www.dummies.com/extras/matlab.Updates: Sometimes changes happen. For example, we might not have seen an upcoming change when we looked into our crystal balls during the writing of this book. In the past, this possibility simply meant that the book became outdated and less useful, but you can now find updates to the book at http://www.dummies.com/extras/matlab.In addition to these updates, check out the blog posts with answers to reader questions and demonstrations of useful book-related techniques at http://blog.johnmuellerbooks.com/.
Companion files: Hey! Who really wants to type all the code in the book and reconstruct all those plots by hand? Most readers would prefer to spend their time actually working with MATLAB and seeing the interesting things it can do, rather than typing. Fortunately for you, the examples used in the book are available for download, so all you need to do is read the book to learn MATLAB usage techniques. You can find these files at http://www.dummies.com/extras/matlab.It’s time to start your MATLAB adventure! If you’re completely new to MATLAB, you should start with Chapter 1 and progress through the book at a pace that allows you to absorb as much of the material as possible.
If you’re a novice who’s in an absolute rush to get going with MATLAB as quickly as possible, you could skip to Chapter 2 with the understanding that you may find some topics a bit confusing later. Skipping to Chapter 3 is possible if you already have MATLAB installed, but be sure to at least skim Chapter 2 so that you know what assumptions we made writing this book.
Readers who have some exposure to MATLAB can save reading time by moving directly to Chapter 5. You can always go back to earlier chapters as necessary when you have questions. However, it’s important that you understand how each technique works before moving to the next one. Every technique, coding example, and procedure has important lessons for you, and you could miss vital content if you start skipping too much information.
Part I
For great online content, check out http://www.dummies.com.
In this part …
Discover why you want to start using MATLAB to speed your calculation.Install MATLAB on your particular system.Start working with MATLAB to become better acquainted with the program.Perform some simple tasks to understand the interface.Become familiar with the MATLAB file system.Chapter 1
In This Chapter
Understanding how MATLAB fits in as a tool for performing math tasks
Seeing where MATLAB is used today
Discovering how to get the most from MATLAB
Overcoming the MATLAB learning curve
Math is the basis of all our science and even some of our art. In fact, math itself can be an art form — consider the beauty of fractals (a visual presentation of a specialized equation). However, math is also abstract and can be quite difficult and complex to work with. MATLAB makes performing math-related tasks easier. You use MATLAB to perform math-related tasks such as
Numerical computationVisualizationProgrammingThis chapter introduces you to MATLAB, an application that performs a variety of math tasks. It helps you understand the role that MATLAB can play in reducing the overall complexity of math and in explaining math-related information to others more easily. You also discover that MATLAB is already used by a number of different organizations to perform real-world tasks in a manner that improves accuracy, efficiency, and consistency. Of course, knowing how you can translate these benefits of MATLAB to your own workplace is important.
Because MATLAB can do so much, it does have a learning curve. This chapter also discusses what you can do to reduce the learning curve so that you become productive much faster. The less time you spend learning about MATLAB, the more time you spend applying math to your particular specialty, and the better the results you achieve. Getting things done quickly and accurately is the overall goal of MATLAB.
MATLAB is all about math. Yes, it’s a powerful tool and yes, it includes its own language to make the execution of math-related tasks faster, easier, and more consistent. However, when you get right down to it, the focus of MATLAB is the math. For example, you could type 2 + 2 as an equation and MATLAB would dutifully report the sum of 4 as output. Of course, no one would buy an application to compute 2 + 2 — you could easily do that with a calculator. So you need to understand just what MATLAB can do. The following sections help you put MATLAB into perspective so that you better understand how you can use it to perform useful work.
Today’s computers are mostly Turing machines, named after the British mathematician Alan Turing (1912–1954). The main emphasis of a Turing machine is performing tasks step by step. A single processor performs one step at a time. It may work on multiple tasks, but only a single step of a specific task is performed at any given time. Knowing about the Turing machine orientation of computers is important because MATLAB follows precisely the same strategy. It, too, performs tasks one step at a time in a procedural fashion. In fact, you can download an application that simulates a Turing machine using MATLAB at http://www.mathworks.com/MATLABcentral/fileexchange/23006-turing-machine-emulator/content/@turing/turing.m. The code is surprisingly short.
Don’t confuse the underlying computer with the programming languages used to create applications for it. Even though the programs that drive the computer may be designed to give the illusion of some other technique, when you look at how the computer works, you see that it goes step by step. If you’ve never learned how computers run programs, this information is meaningful background. Refer to the nearby sidebar “Understanding how computers work” for a discussion of this important background information.
Many older programmers are geeks who punched cards before TVs had transistors. One advantage of punching cards is getting to physically touch and feel the computer’s instructions and data. This physicality gave programmers a good understanding of what happens when a program runs.
Today, the instructions and data are stored as charges of electrons in tiny pieces of silicon too small to be seen through even the most powerful optical microscope. Today’s computers can handle much more information much more quickly than early machines. But the way they use that information is basically the same as early computers.
In those old card decks, programmers wrote one instruction on each card. After all the instructions, they put the data cards into a card reader. The computer read a card and the computer did what the card told it to do: Get some data, get more data, add it together, divide, and so on until all the instructions were executed.
A series of instructions is a program. The following figure shows a basic schematic block diagram of how a computer works.
Unchanged from the old days, when cards were read one at a time, computer instructions continue to be read one at a time. The instruction is executed, and then the computer goes to the next instruction. MATLAB executes programs in this manner as well.
It’s important to realize that the flow of a program can change. Computers can make decisions based on specific criterion, such as whether something is true or false, and take the route indicated for that decision. For example, when the computer has read all the data for a task, the program tells the computer to quit reading data and start doing calculations. Mapping how the computer executes programs is called a flow chart, which is similar to a road map with intersections where decisions must be made. MATLAB relies on well-designed flow charts to make it easy to see what the computer will do, when it will do it, and how it will accomplish the required tasks.
The whole concept of a program may seem foreign to many — something that only geeks would ever love — but you’ve already used the concept of a program before. When using a calculator, you first think of the steps and numbers you want to enter and in what sequence to enter them to solve your problem. A program, including a MATLAB program, is simply a sequence of similar steps stored in a file that the computer reads and executes one at a time. You don’t need to fear computer programming — you’ve probably done something very similar quite often and can do it easily again.
MATLAB is a computer programming language, not merely a calculator. However, you can use it like a calculator, and doing so is a good technique to try ideas that you might use in your program. When you get past the experimentation stage, though, you usually rely on MATLAB to create a program that helps you perform tasks
ConsistentlyEasilyQuicklyWith these three characteristics in mind, the following sections explore the idea of MATLAB’s being more than a simple calculator in greater detail. These sections don’t tell you everything MATLAB can do, but they do provide you with ideas that you can pursue and use to your own advantage.
Schools currently have a strong emphasis on Science, Technology, Engineering, and Math (STEM) topics because the world doesn’t have enough people who understand these disciplines to get the required work done. Innovation of any sort requires these disciplines, as do many practical trades. MATLAB has a rich and large toolbox for STEM that includes
StatisticsSimulationImage processingSymbolic processingNumerical analysisMany developers start learning their trade using an older language named Basic. Originally, it was spelled BASIC, for Beginner’s All-Purpose Symbolic Instruction Code. The intent behind Basic was to make the language simple. MATLAB retains the simplicity of Basic, but with a much larger toolbox to solve STEM problems. The idea is that you have better things to do than learn how to program using a complex language designed to meet needs that your programs will never address.
Everything has trade-offs. MATLAB is specifically designed to meet the needs of people who use math for learning or to make a living. It gets rid of the complexity found in many other languages and keeps things simple so that you can focus on your work rather than on the tool you’re using to do it. However, in pursuing simplicity, MATLAB is also less flexible than other programming languages, provides fewer advanced features for tasks you’ll never perform anyway, and offers fewer generic tools. MATLAB is designed to meet specific needs rather than work as a general-purpose language.
It’s important to know how to use any application you adopt, but it’s equally important to know when to use it and what it can actually do for your organization. If you don’t have a strong reason to use an application, the purchase will eventually sit on the shelf collecting dust. This bit of dust collecting happens far too often in corporations around the world today because people don’t have a clear idea of why they even need a particular application. Given that MATLAB can perform so many tasks, you don’t want it to just sit on the shelf. The following sections can help you build a case for buying and then using MATLAB in your organization.
Writing programs is all about telling the computer to perform a task one step at a time. The better your language tells the computer what to do, the easier the computer will be to use and the less time you’ll spend getting it to perform a given task.
Starting with the C and Pascal computer languages, developers began creating structured environments. In such an environment, a map of instructions and decisions doesn’t look like a bowl of spaghetti — hard to follow and make sense of — but looks more like a tree, with a trunk and branches that are much easier to follow and understand. MATLAB places a strong emphasis on structure (for example, in the way it organizes data and in the manner in which you write code), which means that you spend a lot more time doing something fun and a lot less time writing code (because the structure means that you work with data in a consistent manner).
Structure does come with a price (there really are trade-offs to everything). Early developers could write an application quickly because they had few rules to follow. Because newer languages do enforce structure (making the code easier to read and update later), you have to spend time learning the rules. The rules are what produce the learning curve in MATLAB that you need to consider as part of working with the product. Make sure that you set realistic goals and establish a timetable that reflects the need to learn programming rules. You can’t rush through the MATLAB learning process and expect to do anything useful at the end.
You may have heard of Object-Oriented Programming (OOP). It’s a discipline that helps developers create applications based on real-world models. Every element of an application becomes an object that has specific characteristics and can perform specific tasks. This technology is quite useful to developers because it helps them create extremely complex applications with fewer errors and less coding time.
However, OOP isn’t something you need to know in order to work through various types of math problems. Even though you can solve difficult math problems using languages that do support OOP, STEM users can exploit most of MATLAB’s power without OOP. The lack of an OOP requirement means that you can get up and running with MATLAB far faster than you could with a conventional modern programming language and without a loss of the functionality that you need to perform math tasks.
OOP does serve a useful purpose — just not a purpose that you need when creating math models. Leave the complex OOP languages to developers who are creating the software used to access huge databases, or developing a new operating system. MATLAB is designed to make things easy for you.
MATLAB provides a toolbox designed to meet the specific needs of STEM users. In contrast to a general programming language, this toolbox provides specific functionality needed to meet certain STEM objectives. Here is just a small sample of the areas that are addressed by the tools you find in the MATLAB toolbox:
AlgebraLinear algebra — many equations dealing with many unknownsCalculusDifferential equationsStatisticsCurve fittingGraphingPreparing reportsProgramming languages are often rated by their generation. For example, a first-generation language works side by side with the hardware. It’s the sort of language that programmers used when computers first appeared on the scene. Nothing is wrong with working directly with the hardware, but you need specialized knowledge to do it, and writing such code is time consuming. A first-generation language is so hard to use that even the developers decided to create something better — second-generation languages! (Second-generation languages, such as Macro Assembler [MASM] are somewhat human-readable, must be assembled into executable code before use, and are still specific to a particular processor.)
Most developers today use a combination of third-generation languages such as C, C++, and Java, and fourth-generation languages such as Structured Query Language (SQL). A third-generation language gives the developer the kind of precise control needed to write exceptionally fast applications that can perform a wide array of tasks. Fourth-generation languages make asking for information easier. For the MATLAB user, the promise of fourth-generation languages means being able to work with collections of data, rather than individual bits and bytes, making it easier for you to focus on the task, instead of the language.
As languages progress from first generation to fourth generation (and beyond), they become more like human language. For example, you might write something like FIND ALL RECORDS WHERE LAST_NAME EQUALS ‘SMITH’. It’s not quite human language, but close enough that most people can follow it. You tell the computer what to do, but the computer actually decides how to do it. Such languages are useful because they take the burden of interacting with the computer hardware off the language user and place it on the automation that supports the language.
MATLAB employs a fourth-generation language to make your job a lot easier. The language isn’t quite human, but it’s also a long way away from the machine code that developers used to write to make computers work. Using MATLAB makes you more efficient because the language is specifically designed to meet the needs of STEM users (just as SQL is designed to meet the needs of database administrators and developers who need to access large databases).
An application isn’t very useful if you can’t perform real-world tasks with it. Many applications out there are curiosities — they may do something interesting, but they aren’t really practical. MATLAB is popular among STEM users whose main goal is productively solving problems in their particular field — not problems unique to computer programming. You can find MATLAB used in these kinds of professions:
ScientistsEngineersMathematiciansStudentsTeachersProfessorsStatisticiansControl technologyImage-processing researchersSimulation usersOf course, most people want to hear about actual users who are employing the product to do something useful. You can find such a list at http://www.mathworks.com/company/user_stories/product.html. Just click the MATLAB entry to see a list of companies that use MATLAB to perform real-world tasks. For example, this list tells you that the Centers for Disease Control (CDC) uses MATLAB for polio virus sequencing (see http://www.mathworks.com/company/user_stories/Centers-for-Disease-Control-and-Prevention-Automates-Poliovirus-Sequencing-and-Tracking.html). You also find that the National Aeronautic and Space Administration (NASA) used MATLAB when creating the model for the X-43 — the craft that recently achieved mach 10 (read about it at http://www.mathworks.com/company/user_stories/NASAs-X-43A-Scramjet-Achieves-Record-Breaking-Mach-10-Speed-Using-Model-Based-Design.html). The list of companies goes on and on. Yes, MATLAB really is used for important tasks by a large number of companies.
At this point, you may have decided that you absolutely can’t get by without obtaining your own personal copy of MATLAB. If that’s the case, you really do need to know a little more about it in order to get the most value for your money. The following sections provide a brief overview of the skills that are helpful when working with MATLAB. You don’t need these skills to perform every task, but they all come in handy for reducing the overall learning curve and making your MATLAB usage experience nicer.
Most complex applications require that you have basic computer skills, such as knowing how to use your mouse, work with menu systems, understand what a dialog box is all about, and perform some basic configuration tasks. MATLAB works like other computer programs you own. It has an intuitive and conventional Graphical User Interface (GUI) that makes using MATLAB a lot easier than employing pad and pen. If you’ve learned to use a GUI operating system such as Windows or the Mac OS X, and you also know how to use an application such as Word or Excel, you’ll be fine.
This book points out MATLAB peculiarities. In addition, you have access to procedures that you can use to make your tasks easier to perform. The combination of these materials will make it easier for you to work with MATLAB even if your computer skills aren’t as finely honed as they could be. The important thing to remember is that you can’t break anything when working with MATLAB. In fact, we encourage trial and error because it’s a great learning tool. If you find that an example doesn’t quite work as anticipated, close MATLAB, reopen it, and start the example over again. MATLAB and your computer are both more forgiving than others may have led you to believe.
You need to have the right level of knowledge to use MATLAB. Just as using SQL is nearly impossible without a knowledge of database management, using MATLAB is hard without the proper math knowledge. MATLAB’s benefits become evident when applied to trigonometry, exponentials, logarithms, and higher math.
This book assumes that you have a certain level of math knowledge. The math behind the exercises isn’t explained to any large degree unless the explanation helps you understand the MATLAB programming language better. However, many sites online cater to math knowledge. For example, you can find a host of tutorials at http://www.analyzemath.com/. These tutorials come complete with exercises that help you understand the math behind the MATLAB examples in this book.
One of the more significant problems in understanding how to use any language is the procedure. The point was driven home to one fellow at an early age when his teacher assigned his class the task of writing a procedure for making toast. Every student carefully developed a procedure for making toast, and on the day the papers were turned in, the teacher turned up with a loaf of bread and a toaster. She dutifully followed the instructions each child provided to the letter. All the children failed at the same point. Yes, they forgot to take the bread out of the wrapper. You can imagine what it was like trying to shove a single piece of bread into the toaster when the piece was still in the wrapper along with the rest of the bread.
Programming can be (at times) just like the experiment with the toast. The computer takes you at your word and follows to the letter the instructions you provide. The results may be not what you expected, but the computer always follows the same logical course. Having previous knowledge of a procedural language, such as C, Java, C++, or Python, will help you understand how to write MATLAB procedures as well. You have already developed the skill required to break instructions into small pieces and know what to do when a particular piece is missing. Yes, you can use this book without any prior programming experience, but the prior experience will most definitely help you get through the chapters must faster and with fewer errors.
This is a For Dummies book, so it takes you by the hand to explore MATLAB and make it as easy to understand as possible. The goal of this book is to help you use MATLAB to perform at least simple feats of mathematical magic. It won’t make you a mathematician and it won’t help you become a developer — those are topics for other books. When you finish this book, you will know how to use MATLAB to explore STEM-related topics.
Make sure that you also check out the blog for this book at http://blog.johnmuellerbooks.com/categories/263/matlab-for-dummies.aspx. This is the place to look for updates and additional information. Also, the blog offers answers to commonly asked questions — questions asked by people just like you. You can also write the authors: John ([email protected]) and Jim ([email protected]) with your book-related questions. We want to ensure that you have a great reading experience and can get everything possible from this book.
Even easy programming languages have a learning curve. If nothing else, you need to discover the techniques that developers use to break tasks into small pieces, ensure that all the pieces are actually there, and then place the pieces in a logical order. Creating an orderly flow of steps that the computer can follow can be difficult, but this book leads you through the process a step at a time.
To help you understand MATLAB, this book compares how to accomplish a task in MATLAB with something you’re used to, such as a spreadsheet or calculator. You learn by doing. Try the examples in this book and invent some of your own. Try variations and experiment. MATLAB’s not too tough — you, too, can discover how to use MATLAB.
Chapter 2
In This Chapter
Obtaining and installing your copy of MATLAB
Starting MATLAB and working with the interface
Before you can use MATLAB to do anything productive, you need a copy of it installed on your system. Fortunately, you can obtain a free trial version that lasts 30 days. If you’re diligent, you can easily complete this book in that time and know for certain whether you want to continue using MATLAB as a productivity aid. The point is that you need a good installation, and this book helps you obtain that goal.
After you have MATLAB installed, it’s important to introduce yourself to the interface. This chapter provides you with an overview of the interface, not a detailed look at every feature. However, overviews are really important because working with lower-level interface elements is hard if you don’t have the big picture. You may actually want to mark this chapter in some way so that you can refer back to the interface information.
A problem that anyone can encounter is getting a bad product installation or simply not having the right software installed. When you can’t use your software properly, the entire application experience is less than it should be. The following sections guide you through the MATLAB installation so that you can have a great experience using it.
Before you go any further, you need to verify that your system will actually run MATLAB. At a minimum, you need 3GB of free hard drive space and 2GB of RAM to use MATLAB effectively. (It can run on systems with fewer resources, but you won’t be happy with the performance.) You also need to know which platforms MATLAB supports. You can use it on these systems:
Windows (3GB free disk space, 2GB RAM) Windows 8.1Windows 8Windows 7 Service Pack 1Windows Vista Service Pack 2Windows XP Service Pack 3Windows XP x64 Edition Service Pack 2Windows Server 2012Windows Server 2008 R2 Service Pack 1Windows Server 2008 Service Pack 2Windows Server 2003 R2 Service Pack 2Mac OS X Mac OS X 10.9 (Mavericks)Mac OS X 10.8 (Mountain Lion)Mac OS X 10.7.4+ (Lion)Linux Ubuntu 12.04 LTS, 13.04, and 13.10Red Hat Enterprise Linux 6.xSUSE Linux Enterprise Desktop 11 SP3Debian 6.xLinux users may find that other distributions work. However, the list of Linux systems represents those that are tested to work with MATLAB. If you try MATLAB on your unlisted Linux system and find that it works well, please let John know (at [email protected]) and he’ll mention these other systems in a blog post. The point is that you really do need to have the right platform to get good results with MATLAB. You can always obtain the current minimum requirements for MATLAB at http://www.mathworks.com/support/sysreq/current_release/index.html.
Before you can work with MATLAB, you need a copy installed on your system. Fortunately, you have a number of methods at your disposal. Here are the three most common ways of getting MATLAB:
Get the trial version from https://www.mathworks.com/programs/trials/trial_request.html.Obtain a student version of the product from https://www.mathworks.com/academia/student_version/.Buy a copy from http://www.mathworks.com/pricing-licensing/index.html.In most cases, you need to download the copy of MATLAB or the MATLAB installer onto your system after you fill out the required information to get it. Some users choose to receive a DVD in the mail instead of downloading the product online. No matter which technique you use, you eventually get a copy of MATLAB to install.
The method you use to install MATLAB depends on the version you obtain and the media used to send it to you. For example, there is a method for installing MATLAB from DVD and an entirely different method when you want to download the installer and use an Internet connection. Administrators and users also have different installation procedures. Use the table at http://www.mathworks.com/help/install/ug/choose-installation-procedure.html to determine which installation procedure to use.
MathWorks provides you with substantial help in performing the installation. Before you contact anyone, be sure to look through the materials on the main installation page at http://www.mathworks.com/help/install/index.html. It’s also possible to obtain installation help at http://www.mathworks.com/support/install-matlab.html. Take the time to review the material that MathWorks provides before you push the panic button. Doing so will save time and effort.
After you complete the MATLAB installation, you must activate the product. Activation is a verification process. It simply means that MathWorks verifies that you have a valid copy of MATLAB on your system. With a valid copy, you obtain support such as updates to your copy of MATLAB as needed.
As with installation, you have a number of activation types to use with MATLAB that depend on the product version and how you’re using the product. The chart at http://www.mathworks.com/help/install/license/activation-types.html tells you about these activation types and helps you make a selection. The matrix at http://www.mathworks.com/help/install/license/license-option-and-activation-type-matrix.html tells you whether your particular version of MATLAB supports a specific activation type. For example, the individual license doesn’t support the Network Named User activation type.
MATLAB automatically asks you about activation after the installation process is complete. You don’t need to do anything special. However, you do want to consider the type of activation you want to perform — which type of activation will best meet your needs and those of your organization.
Most applications have similar interface functionality. For example, if you click a button, you expect something to happen. The button usually contains text that tells you what will happen when you click it, such as closing a dialog box by clicking OK or Cancel. However, the similarities aren’t usually enough to tell you everything you need to know about the interface. The following sections provide an overview of the MATLAB interface so that you can work through the chapters that follow with greater ease. These sections don’t tell you everything about the interface, but you do get enough information to feel comfortable using MATLAB.
When you start MATLAB for the first time (after you activate it), you see a display containing a series of blank windows. It’s not all that interesting just yet because you haven’t done anything with MATLAB. However, each of the windows has a special purpose, so it’s important to know which window to use when you want to perform a task.
It’s possible to arrange the windows in any order needed. Figure 2-1 shows the window arrangement used throughout the book, which may not precisely match your display. The “Changing the MATLAB layout” section of this chapter tells you how to rearrange the windows so that you can see them the way that works best when you work. Here is a brief summary of the window functionality.
Home tab: The Home tab of the Ribbon interface (a bar that provides access to various MATLAB features, such as creating a new script or importing data) is where you find most of the icons you use to create and use MATLAB formulas. It’s the tab you use most often. Also on the interface is a Plots tab (for creating graphic presentations of your formulas) and an Apps tab (for obtaining new applications to use with MATLAB). MATLAB calls the Ribbon interface the Toolstrip, so that’s the name we use throughout the book.Figure 2-1: The initial view of MATLAB is pretty much empty space.
You can change the QAT to meet your needs. To add an icon to the QAT, right-click its entry in the Toolstrip and choose Add to Quick Access Toolbar from the context menu. If you want to remove an icon from the QAT, right-click its entry in the QAT and choose Remove from the Quick Access Toolbar from the context menu.
Minimize Toolstrip: If you find that the Toolstrip is taking up too much space, you can click the Minimize Toolstrip icon to remove it from view. To restore the Toolstrip, simply click the Minimize Toolstrip icon again.When the Toolstrip is minimized, you can still see the three tabs — Home, Plots, and Apps. Click a tab to reveal the Toolstrip long enough to use a MATLAB feature. As soon as you select a Toolstrip feature or click in another MATLAB area, the Toolstrip disappears again. Using this technique allows you full access to the MATLAB features but keeps the Toolstrip hidden to save space.
Command window: You type formulas and commands in this window. After you type the formula or command and press Enter, MATLAB determines what it should do with the information you typed. You see the Command window used later in this chapter.Workspace window: The Workspace window contains the results of any tasks you ask MATLAB to perform. It provides a scratchpad of sorts that you use for calculations. The Workspace window and Command window work hand in hand to provide you with a complete view of the work you perform using MATLAB.Command History window: In some cases, you want to reissue a formula or command. The Command History window acts as your memory and helps you restore formulas and commands that you used in the past. You see the Command History window used later in this chapter.Status bar: It’s important to know the current MATLAB state — whether MATLAB is ready to perform additional work or not. The status bar normally contains one word, Ready, which tells you that MATLAB is ready to perform tasks. However, you need to watch this window when performing complex tasks to see what MATLAB is doing at any given time.Details window: The Details window shows specifics about any file you select in the Current Folder window.Current Folder window and Address Field: The Current Folder window contains a listing of the files you’ve created in the current folder — files you’d use to store any data you create in MATLAB, along with any scripts or functions you’d use to manipulate data). The Current Folder is listed in the Address Field text box that appears directly below the Toolstrip. Changing the Address Field text box content also changes the content of the Current Folder window.The Command window is where you perform most of your experimentation. This chapter shows how to perform really simple tasks using the Command window, but as the book progresses, you see that the Command window can do quite a lot for you. The following sections describe some of the ways in which you can use the Command window to learn more about MATLAB.