Programming Fundamentals Using MATLAB - M. Weeks - E-Book

Programming Fundamentals Using MATLAB E-Book

M. Weeks

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

This book introduces MATLAB syntax and environment, ideal for beginners with no programming background. The first four chapters cover basic programming concepts, computing terminology, MATLAB syntax, control structures, operators, arrays, and matrices.
Next, the book explores grouping data, working with files, creating images, building graphical user interfaces, experimenting with sound, and debugging. The final chapters present case studies on using MATLAB with tools like Arduino, Linux, Git, and Mex, essential for basic programming knowledge.
Understanding MATLAB is crucial for data analysis and technical computing. This book transitions readers from basics to advanced topics, blending theoretical knowledge with practical applications. Companion files with code and four-color figures enhance learning, making this an essential resource for mastering MATLAB.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 779

Veröffentlichungsjahr: 2024

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



PROGRAMMINGFUNDAMENTALSUSING MATLAB®

LICENSE, DISCLAIMER OF LIABILITY, AND LIMITED WARRANTY

By purchasing or using this book and disc (the “Work”), you agree that this license grants permission to use the contents contained herein, including the disc, but does not give you the right of ownership to any of the textual content in the book / disc or ownership to any of the information or products contained in it. This license does not permit uploading of the Work onto the Internet or on a network (of any kind) without the written consent of the Publisher. Duplication or dissemination of any text, code, simulations, images, etc. contained herein is limited to and subject to licensing terms for the respective products, and permission must be obtained from the Publisher or the owner of the content, etc., in order to reproduce or network any portion of the textual material (in any media) that is contained in the Work.

MERCURY LEARNING AND INFORMATION (“MLI” or “the Publisher”) and anyone involved in the creation, writing, or production of the companion disc, accompanying algorithms, code, or computer programs (“the software”), and any accompanying Web site or software of the Work, cannot and do not warrant the performance or results that might be obtained by using the contents of the Work. The author, developers, and the Publisher have used their best efforts to insure the accuracy and functionality of the textual material and/or programs contained in this package; we, however, make no warranty of any kind, express or implied, regarding the performance of these contents or programs. The Work is sold “as is” without warranty (except for defective materials used in manufacturing the book or due to faulty workmanship).

The author, developers, and the publisher of any accompanying content, and anyone involved in the composition, production, and manufacturing of this work will not be liable for damages of any kind arising out of the use of (or the inability to use) the algorithms, source code, computer programs, or textual material contained in this publication. This includes, but is not limited to, loss of revenue or profit, or other incidental, physical, or consequential damages arising out of the use of this Work.

The sole remedy in the event of a claim of any kind is expressly limited to replacement of the book and/or disc, and only at the discretion of the Publisher. The use of “implied warranty” and certain “exclusions” vary from state to state, and might not apply to the purchaser of this product.

(Companion files are also available for downloading from the publisher; [email protected] to request them.)

PROGRAMMINGFUNDAMENTALSUSING MATLAB

MICHAEL C. WEEKS, PHD(Georgia State University)

MERCURY LEARNING AND INFORMATION

Dulles, Virginia

Boston, MassachusettsNew Delhi

Copyright ©2020 by MERCURY LEARNINGAND INFORMATION LLC. All rights reserved.

This publication, portions of it, or any accompanying software may not be reproduced in any way, stored in a retrieval system of any type, or transmitted by any means, media, electronic display or mechanical display, including, but not limited to, photocopy, recording, Internet postings, or scanning, without prior permission in writing from the publisher.

Publisher: David Pallai

MERCURY LEARNING AND INFORMATION

22841 Quicksilver Drive

Dulles, VA 20166

[email protected]

www.merclearning.com

(800) 232-0223

Michael Weeks. Programming Fundamentals Using MATLAB.

ISBN: 978-1-68392-555-2

The publisher recognizes and respects all marks used by companies, manufacturers, and developers as a means to distinguish their products. All brand names and product names mentioned in this book are trademarks or service marks of their respective companies. Any omission or misuse (of any kind) of service marks or trademarks, etc. is not an attempt to infringe on the property of others.

Library of Congress Control Number: 2020939910

202122 321 Printed on acid-free paper in the United States of America

Our titles are available for adoption, license, or bulk purchase by institutions, corporations, etc. For additional information, please contact the Customer Service Dept. at (800) 232-0223(toll free).

Digital versions of our titles are available at: www.academiccourseware.com and other electronic vendors. Companion files are available from the publisher by writing to [email protected]. The sole obligation of MERCURY LEARNING AND INFORMATION to the purchaser is to replace the book and/or disc, based on defective materials or faulty workmanship, but not based on the operation or functionality of the product.

I dedicate this book to my son, Samuel. I hope that he finds the same joy in mathematics that I have found.

CONTENTS

List of Figures

List of Tables

Preface

Chapter 1:  The MATLAB Environment and Programming Terminology

1.1Algorithms

1.2Programs

1.3Compilers and Errors

1.4Variables

1.5Data Types

1.6A Preview of Basic MATLAB Commands

1.7Key Shortcuts

1.8Writing Programs that are Easy to Read

1.9Debugging Techniques

1.10Common Unix Commands

1.11The MATLAB Mobile Application

1.12Summary

Exercises

Projects

Chapter 2:  MATLAB Programming Basics

2.1Ranges

2.2Strings and Formatting Output

2.3Examples of MATLAB Commands

2.3.1Assignment

2.3.2Conditionals

2.3.3Loops

2.3.4Ways to Alter Flow Within a Loop

2.3.5Infinite Loops

2.3.6Error Handling

2.3.7Summary of MATLAB Program Structures

2.4Examples Using Loops and Conditionals

2.5Example of a While Loop, with User Input

2.6Common MATLAB Functions

2.7Plot

2.8Creating Our Own Functions

2.8.1Multiple Inputs and Multiple Outputs

2.8.2Variable Argument Input

2.9Pass by Value or Reference

2.10File Extensions

2.11Checking If a Variable Exists

2.12Programming Tips

2.13A Variable Naming Example

2.14Algorithmic Thinking

2.15Fluidity of Data

2.16Hexadecimal and Binary

2.17Summary

Exercises

Projects

Chapter 3:  Relational Operators, Boolean Values, and Logical Operators

3.1Relational Operators

3.2Boolean Values

3.3Logical Operators: AND, OR, and NOT

3.4Operator Precedence

3.4.1Establishing Precedence

3.4.2How One and Two Ampersands Differ

3.5Summary

Exercises

Project

Chapter 4:  Arrays and Matrices

4.1Working with Arrays

4.1.1Some Array Functions: Finding the Average

4.1.2More Array Functions: Min, Max, and Median

4.1.3Arrays as Either a Row or a Column

4.2Adding and Deleting from Arrays

4.3Matrices

4.4A Few Matrix Creation Functions

4.4.1Repeating a “Tile”

4.4.2Building a Matrix and Memory Management

4.5Scalar Addition and Matrix Transpose

4.6Arithmetic with Matrices

4.6.1A Matrix of Random Values

4.6.2Ranges as Indices

4.6.3All Indices of a Row or Column

4.7Arrays of Strings

4.7.1The Difference Between Character Arrays and Strings

4.7.2Arrays of Character Arrays

4.7.3Arrays of Strings

4.8Using a Range in Place of a Loop

4.9Summary

Exercises

Project

Chapter 5:  Grouping Data

5.1Grouping Data Together

5.1.1Cells

5.1.2Structures

5.1.3Tables

5.1.4Classes

5.2Defining Classes the Old Way

5.3The “classdef ” Keyword

5.3.1Building a Simple Class

5.3.2An Example Method

5.3.3Constructor

5.3.4Variable Argument List

5.3.5Applying a Class to the Previous Employee Example

5.4Inheriting the “get” and “set” Methods

5.5Comparing Different Ways to Combine Data

5.6Enumeration and Categories

5.6.1Enumeration with a Structure and Numbers

5.6.2Enumeration with a Structure and Strings

5.6.3Enumeration with a Class Definition

5.6.4Categorical Sets

5.7Summary

Exercises

Project

Chapter 6:  File Input and Output

6.1Checking If the File Opened Successfully

6.2Machine Formats and Encodings

6.3Commands to Read from, and Write to, a File

6.4A Few Complete Examples of File I/O

6.5Summary

Exercises

Project

Chapter 7:  Recursion

7.1Function Calls and the Stack

7.2Computing a Factorial with Recursion

7.3Solving a Maze

7.3.1The Maze Solver Function

7.3.2Tracing Through a Small Maze Example

7.4The Knight’s Tour

7.5Summary

Exercises

Project

Chapter 8:  Images

8.1Working with an Image

8.2Converting an Image to Black and White

8.3Making a Simple Image

8.4Color Images

8.5Seeing Different Color Combinations

8.6Color Shifting

8.7Cropping an Image Manually

8.8Making an Image of a Bee

8.9Centering an Image

8.10Making a Rectangular Image Square

8.11Selecting a File with the Graphical User Interface

8.12Bouncing Box: A Simple Animation

8.13Summary

Exercises

Projects

Chapter 9:  Working with a Graphical User Interface

9.1A Simple Pushbutton Example

9.2Message Box

9.3Creating a GUI

9.4Changing the Button’s State

9.5Keeping Data in Global Variables

9.6An Exit Button

9.7Using the “set” Command

9.8How Do We Know What to Get?

9.9Reading Key Presses

9.10Callback Functions and Global Variables

9.10.1Using a Global Variable

9.10.2Commands “evalin” and “assignin”

9.10.3Operating System Utilities “diff ” and “patch”, and MATLAB’s “diff ” and “patch”

9.10.4The “persistent” Keyword

9.11A Callback Problem

9.12A Note about Figure Handles

9.13A Slider Input from A to Z

9.14A “Kitchen Sink” Example

9.15Closing a Figure in Different Ways

9.16Summary

Exercises

Project

Chapter 10:  Sound

10.1Playing a Sound File

10.2Deprecated Sound Commands

10.3Writing a Sound File

10.4Making Sound

10.5Playing Notes

10.6Recording Sound

10.7Working with Two Channels

10.8The Karplus-Strong Algorithm

10.9Summary

Exercises

Project

Chapter 11:  Getting Help and Debugging

11.1How Do You Know If MATLAB Supports a Command?

11.2Debugging—Abstracting Out the Problem

11.3Using the Debugger

11.4Checking Assumptions

11.5Validating Function Inputs

11.6Debugging an Example Comparing Pixel Values

11.7A Special Character Creates an Error

11.8An Error Comparing Strings

11.9Another Debugging Example

11.10Dealing with Errors

11.10.1Seeing What Is There

11.10.2Seeing What Is There, Part 2

11.11Making a Problem Easier

11.12Summary

Exercises

Project

Chapter 12:  Practical MATLAB Programming and Debugging Case Studies: Homebrewing Data

12.1Break It Down, also Known as Divide and Conquer

12.1.1Debugging a Script

12.1.2Debugging a Function

12.2A Problem with Rounding, Where 1.1179999999999999 Should Be 1.118

12.3Fixing a Problem with Apparent Attenuation

12.4Correcting a Refractometer Reading

12.4.1Converting Specific Gravity to Degrees Brix

12.4.2Comparing the Approximate and Exact Answers

12.4.3Refractometer and Hydrometer

12.5A Bug Creates an Apparent Discontinuity

12.6Mash-Step Analysis from Temperature Data

12.6.1Reading and Writing Comma Separated Value Files

12.6.2Making and Correcting Data Files

12.6.3How Did It Get So Cold?

12.6.4Downsampling

12.7Analyzing the Temperature Data

12.8Summary

Exercises

Project

Chapter 13:  Advanced Programming Concerns

13.1How a Problem Grows

13.2Finding a Value in a Sorted List

13.3Sorting

13.4The Traveling Salesman Problem

13.5Evaluating Integrals

13.5.1MATLAB’s Integral Function

13.5.2Calculating This Result Ourselves

13.5.3A Slow and a Fast Way to Find the Change

13.5.4Evaluating Our Own Function as an Integral

13.6Summary

Exercises

Project

Chapter 14:  Other Useful Computing Tools

14.1Linux and Other Tools

14.1.1Libre Office (also Apache Open Office)

14.1.2Firefox and JavaScript

14.1.3Shell Programming

14.1.4An Example Using Shell Commands

14.1.5Running MATLAB from a Terminal Window

14.2LATEX

14.3Git Example

14.4Scilab

14.5Simulink

14.6Mex—Interfacing with C

14.7Mex—Interfacing with C++

14.8Interfacing with Java

14.8.1An Example Java Program

14.8.2Using a Java Program from MATLAB

14.8.3Using the “main” Parameter

14.9MCC, the MATLAB Compiler

14.10MATLAB and HTML

14.11Working with an Arduino

14.11.1Technical Difficulties

14.11.2Working with an External Sensor

14.12Summary

Exercises

Project

Appendix: Solutions to Selected Problems

Bibliography

Index

LIST OF FIGURES

LIST OF TABLES

Table 1.1Common Unix/Linux commands, and equivalents. Many of these commands expect additional information, such as the name of a file.

Table 2.1Common type specifiers for the sprintf command.

Table 3.1Relational operators.

Table 3.2The NOT operation.

Table 3.3The AND operation.

Table 3.4The OR operation.

Table 3.5An example of a bitwise AND operation (bitand).

Table 3.6An example of a bitwise OR operation (bitor).

Table 3.7An example of a bitwise NOT operation (bitcmp).

Table 3.8The precedence of operations, from highest to lowest.

Table 3.9Symbols.

Table 3.10More symbols.

Table 3.11Predefined variables.

Table 3.12Keywords.

Table 3.13A short list of common commands.

Table 3.14A short list of common commands for the operating system, that MATLAB also understands.

Table 5.1Data grouping comparison.

Table 6.1File input and output commands.

Table 6.2Built-in functions to read and write data.

Table 7.1A simple recursion example. Time flows from top to bottom, while stack depth goes from left to right.

Table 7.2How recursion works with the “myfact” function. Time flows from top to bottom, while stack depth goes from left to right.

PREFACE

People use MATLAB in many different fields, such as the growing field of bio-informatics. There are many applications in biology, chemistry, mathematics, engineering and physics, which could benefit from scientists who can program. Given the volume of data for these applications, and the ease of use of MATLAB, this is a natural match.

WHY A BOOK ON MATLAB

This book grew out of an Introduction to MATLAB Programming class. There are other MATLAB books available, but they are often either encyclopedic or version dependent. In the first semester that I taught it, Fall 2006, I found that my students did not have the same software. The classroom had version 6.1, the main lab where students could do homework had version 6.5, while I demonstrated code on my laptop with version 7.0. Some had a student edition of the software, in either version 7.0 or the brand-new 7.2. In other words, there were at least five different versions of the software. A conversation with some students drove this point home. As I talked to a group of three people who were working on a project together, they explained that they split the work into three sets of tasks, and would work on each task one at a time. I asked why they did not work on them together, or go in a different order. Their response was that they could not go backwards, because each person in sequence had a newer version than the previous one.

Standardizing the versions available across the university (at that time) was not feasible. Copies were purchased by different departments at different times. Some even had different toolboxes available; what the math department needed was different than the computer science department. And one biologist might need to work with images, while another needs to do signal acquisition.

Another issue is the amount of material that can be covered in one ­semester. My class involves a laboratory component, meaning it emphasizes problem solving. Class time includes both lecture and the time to work on the computer, at roughly a 3 to 1 ratio. Students who have already studied a programming language pick up MATLAB quickly. In fact, several classes for computer science majors use MATLAB without requiring previous experience with it. For people who have never programmed a computer before, it takes a while before the concepts “sink in.” They need a solid foundation in the basics, with plenty of practice.

This text is meant to get across the basics of MATLAB programming to form that foundation. Chapters are meant to be stand-alone as much as possible. The first chapter covers concepts and terminology that appear again and again. It should be a quick read for people who already have programming experience, but sufficient to get everyone else up and programming.

COMPANION FILES

This book comes with companion files and supplementary materials. For example, many of the figures are available in full color. The example code, functions and programs shown in the text, images, sound, and other data files are also available. All of the full-color figures in the book can be found on the disc (or on the downloadable companion files). The files are also available from the publisher by writing [email protected].

INSTRUCTOR ANCILLARIES

Solutions to the end of chapter exercises and slides are available to instructors upon adoption.

ACKNOWLEDGMENTS

This book was only possible with the support of many people. I could not have written it without the support and understanding of my wife and family.

M.C.WeeksJune 2020

CHAPTER 1

THE MATLAB ENVIRONMENT AND PROGRAMMING TERMINOLOGY

1.1ALGORITHMS

An algorithm, at least in the every-day sense of the term, means a plan to accomplish a task. It is a list of abstract steps to take, in the order given. These steps are “abstract” in the sense that they may be quite complex themselves. Formally, computer scientists describe an algorithm in terms of a Turing Machine, a simple, theoretical device that works on a tape, moving left and right, reading and replacing symbols, according to a set of states (conditions) and instructions. It can lead to an accept state, a reject state, or run forever. Loosely, a state keeps track of the step, with transitions that lead to other states, based on the input. An algorithm is a decidable process for doing something, where decidable means that it ends in the accept or reject state.

To illustrate the informal idea of an algorithm, let’s consider a set of driving directions. Suppose you have a set of instructions that say:

1.Go straight 1 mile, then take a left.

2.At the third light, take a right.

3.When you cross the railroad tracks, take a right directly after them.

4.Stop at the fifth house on your left.

5.If you see a dead-end sign, then you have gone too far. Back up about 500 feet.

Obviously, you must do these steps in order, or you will not get to the destination. Also, a human will understand what each step means, without further explanation. Humans are also great at detecting a problem. For example, what if the railroad tracks were paved over? What if we drive for a long time but never see the railroad tracks? A human would know that something is not correct, and take action (e.g., call the person who gave directions).

Algorithms are specified in an English-like way, called pseudo-code. When we write an algorithm, we are primarily concerned with getting the idea across, and we care about conforming to a machine-understandable pattern to a lesser extent. For example, what if the second line begins with a lower-case character, and the fourth line does not end in a period? While we like consistency, any human would still understand the algorithm.

A loop is when a set of directions repeat, and each repetition is called an iteration. For example, cooking instructions could say to “chop the carrots and set aside. Repeat this with the onions.” If we follow directions that say to do something several times, we might count on our fingers, or perhaps count out loud. The index keeps track of the number of iterations, where a variable stores this value. We start at one, add one to the count every time we repeat, and stop when we reach the maximum. Of course, we could start at the maximum and count down, as some people do with exercises as a motivational trick. We do not even need to count by whole numbers; imagine if you run laps on a quarter-mile track. If you plan to reach a daily goal of 5 miles, and you already ran 2.5 miles this morning, you might start with 2.5 and add 0.25 every time you get back to the starting place. That type of loop iterates for a set number of times, known in advance. Other loops repeat until a condition is met.

Pseudo-code statements are written by humans, for other humans to read. They conform to standards so that they can be directly expressed in a programming language, such as numbering each step, and contain certain keywords like for. Many computer languages have a loop structure invoked by the keyword for, although they differ in specific syntax (how the statement is expressed). Pseudo-code statements are not meant for a computer to understand directly. They are precise about the instruction sequence and control flow, and yet intentionally vague about how some things may be accomplished, such as “display the result.” Whether that result is displayed as text on a screen, printed onto paper, or shown on a high-resolution monitor, does not matter. The programmer who implements the algorithm will determine the best way to display the result with the specific computer language.

1.2PROGRAMS

A program is a list of instructions for a computer to follow. Some people confuse this with an algorithm, but the intended audience for each is different. Algorithms are for humans, while programs are primarily for computers. Programs must be much more detailed than algorithms, since they must specify what to do in a way the computer can understand, as opposed to saying things in a way that a fellow human would follow. Programs must conform to a syntax, the rules of how a programmer specifies commands to the computer. Different computer languages have different syntaxes.

Suppose that we translate the above algorithm to a program, and give it to a computer. It will do exactly what it is told to do. If it does not detect the railroad crossing, it may keep looking for it, forever. We need to test it. We need to provide commands to deal with unexpected conditions, like unused train tracks being paved over.

When we write a program, we call it source code. Most programming languages have a special program called a compiler, meaning that the program will be translated (compiled) into a form that the computer’s microprocessor (also called a central processing unit, or CPU) can use. The compiled code is specific to that computer’s type of CPU, i.e., a program compiled on a PowerPC-based Mac is incompatible with a Sun SPARC processor, as well as an Intel-based personal computer. For that matter, a program compiled on a PowerPC-based Mac is not compatible with the recent Intel-based Macs. The compiler generates an executable program that other people can use on their computers, and may even pay for. Most people mean the executable program when they say the word software. In contrast, hardware means the physical computer. To run a program means to execute it; to tell the computer that it should follow the directions specified by the program. By the way, “app” is just a trendy word for application, and it means the same thing as software, although often it is software made specifically for a mobile device.

In some companies, the executable programs are sold while the source code used to make them are carefully guarded secrets. An analogy is the recent news item from Coca-Cola: while millions of people buy Coke products every day, an employee allegedly obtained the secret formula and tried to sell it to rival Pepsi for over a million dollars [1]. Needless to say, the plot was discovered and the people involved were arrested. Similar to the way soft drink makers sell their products but do not disclose exactly how they make them, a software company may write a useful program, and sell only the executable version of it. We call this closed source. The average (home) user would not know what to do with the source code if they had it, but a programmer could examine it for errors or add features and potentially make it better. Of course, an unscrupulous programmer could change it just enough to make it appear to be their own work, then sell the executable code. Or they could find weaknesses in the code, and use them for malicious purposes, like taking over someone else’s machine.

A different approach is the open source movement, where source code is available (usually for free). An obvious question is, “How do you make money by giving something away for free?” One answer is convenience. Consider an oil-change for your car. If you have ever changed the oil in your car, it was probably not difficult, but it was a messy experience. Why bother to get dirty when you can drive to a quick-change facility and (for a reasonable fee) have someone else do it in only a few minutes? Similarly, a technical person may find the nominal cost for a CD-ROM (or other media) of software to be well worth the expense, instead of spending an evening downloading code, configuring it, compiling it, etc. Also, service is a potential area of revenue for an open-source software company, as many users will pay a yearly fee for the ability to call a technician who is very familiar with the software. Users will also pay to subscribe to automatic updates. But what if an unscrupulous person finds problems in the software that they can exploit? Of course this is a potential problem, but what the open-source community found is that many good people will spot potential problems, and updates are quickly disseminated.

Related to open-source software is the open standard. A good example of this is the portable document format (PDF), associated with the Adobe Acrobat program. While Acrobat is closed source software, the portable document format standard is an open standard; it is available on the Internet. (Actually, the portable document format standard is based on postscript, another open standard.) This means that while you are not going to have access to the source code for Acrobat, you can still write your own program to read or write portable document format files. Not all standards are open, and the use of closed standards has become an area of debate. The state of Massachusetts recently passed a law requiring state employees to use an open standard for documents, based on the idea that their citizens have a right to public information in an open format [2].

MATLAB is a product of The MathWorks, a company based in Massachusetts. MATLAB is a program that provides an environment for programming. (Take a deep breath—it is really not that complicated!) Programs written according to the MATLAB syntax are read and interpreted by the MATLAB programming environment. Or, you could say that MATLAB programs are read and executed by the MATLAB program. Since this results in confusion, we will take care to call the MATLAB program the “MATLAB programming environment” or simply “MATLAB,” and use “MATLAB program” to mean a program written in the syntax that MATLAB understands.

While it is closed source software in the sense that you are not going to have access to the source code, you will find that many MATLAB functions are available for inspection. Programs are stored in an open standard, called the “MATLAB syntax” above. MATLAB programs are text files that have “.m” for the extension. For example, you might name a program to calculate your taxes “mytaxes.m” if you wrote it in MATLAB. By the way, the Objective-C language also uses “.m” for its extension. If you click on a file with a “.m” extension, your computer may call up a different programming environment than MATLAB. See Section 2.10 for other common file extensions used in the MATLAB environment.

With MATLAB, you can interact with the command window, typing commands one by one, getting feedback, and revising the commands as needed. You might have a series of commands that you would like to save and use again later. In the command window, typing “edit” calls up MATLAB’s editor, similar to other text-processing software that you have used. From here, you can copy and paste the commands into the editor, then save it under a name ending in .m, although the editor will likely take care of that detail for you. That file is a program, also called other names like code, source-code, and script. Later, we will cover functions, although for the moment, you can tell scripts and functions apart by the function keyword. If a MATLAB file contains the word function at the start of the first line of commands, then it is a function. Otherwise, it is a script.

1.3COMPILERS AND ERRORS

The compiler translates the entire program all at once. A syntax error (similar to the missing period in the above algorithm) would stop a computer from understanding the directions. It would essentially say, “I do not understand these directions, so I cannot follow them.” It may stop trying at this point. If it keeps going, any further errors reported might be a result of the first one, so it is good practice to examine the error messages in order. Syntax errors will be fixed by the programmer. A different type of error called a logic error occurs when the program does something that the programmer did not intend. The commands may make sense individually, but not when considered together. A computer does not make judgment calls (unless we specifically tell it how to do this). It will perform each command, doing precisely what we tell it to do. But it may not do what we want it to do! We also call a logic error a bug, coming from a story about the computing pioneer Grace Hopper discovering a moth that had short-circuited a computer, causing an error.

Here is an example of a logic error. Suppose you write down the steps to calculate employees’ gross pay. Some work part-time, some work full-time. Many of them work overtime, and they are paid a “time and a half” bonus for overtime. Your instructions may look like this:

1.if the number of hours worked < 40, then pay=(hours worked)*(pay rate)

2.if the number of hours worked > 40, then pay=(hours worked)*1.5*(pay rate)

If a computer were to process those directions, many people would receive weird paychecks, perhaps even negative amounts! The instructions specify what to do when someone works less than 40 hours, and the instructions also specify what to do when someone works more than 40 hours. But these instructions say nothing about what to do when a person works exactly 40 hours. Thus, we have a logic error. Depending on the computer language, the amount stored in pay might not have been initialized, so the value there is whatever value happened to be there before. One person may receive an automatic payment of negative billions of dollars, while someone else may be credited millions.

MATLAB provides an interpreter. It works a bit differently from a compiler in that it translates line-by-line. We have an interactive environment with MATLAB: you type a command, and it performs it. It gives you immediate feedback (unless you tell it to do something very time-consuming). You can experiment until you have it just right. This iterative approach to programming means to make small changes to a program, test them out, and repeat. It allows us to build a program one step at a time. MATLAB provides a good environment for this approach, since we can enter commands one at a time, and correct them when we make mistakes.

1.4VARIABLES

1.5DATA TYPES

1.6A PREVIEW OF BASIC MATLAB COMMANDS

There are a few basic MATLAB commands that we will use repeatedly, and this section provides a preview. The following chapter gives more details, along with usage examples. First, we have the assignment statement, which uses an equal sign (). Whatever appears on the right side of the equal sign will be evaluated, then stored in the variable that appears on the left side. We can include arithmetic or logical operations on the right side.