# Tamu Math 151 Matlab Assignments Restaurant

Business Economics and Finance with MATLAB®, GIS, and Simulation Models

Business Economics and Finance with MATLAB®, GIS, and Simulation Models Patrick L.Anderson Principal, Anderson Economic Group

CHAPMAN & HALL/CRC A CRC Press Company Boca Raton London New York Washington, D.C.

This edition published in the Taylor & Francis e-Library, 2005. “To purchase your own copy of this or any of Taylor & Francis or Routledge’s collection of thousands of eBooks please go to http://www.ebookstore.tandf.co.uk/.” Library of Congress Cataloging-in-Publication Data Anderson, Patrick L. Business economics and finance with MATLAB, GIS and simulation models/Patrick L. Anderson. p. cm. Includes index. ISBN 1-58488-348-0 (alk. paper) 1. Managerial economics—Mathematical models. I. Title. HD30.22.A53 2004 338.5′01′13–dc22 2003069765 This book contains information obtained from authentic and highly regarded sources. Reprinted material is quoted with permission, and sources are indicated. A wide variety of references are listed. Reasonable efforts have been made to publish reliable data and information, but the author and the publisher cannot assume responsibility for the validity of all materials or for the consequences of their use. Neither this book nor any part may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, microfilming, and recording, or by any information storage or retrieval system, without prior permission in writing from the publisher. The consent of CRC Press LLC does not extend to copying for general distribution, for promotion, for creating new works, or for resale. Specific permission must be obtained in writing from CRC Press LLC for such copying. Direct all inquiries to CRC Press LLC, 2000 N.W. Corporate Blvd., Boca Raton, Florida 33431. Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are used only for identification and explanation, without intent to infringe. Visit the CRC Press Web site at www.crcpress.com © 2005 by Chapman & Hall/CRC Press LLC No claim to original U.S. Government works ISBN 0-203-49465-2 Master e-book ISBN

ISBN 0-203-59406-1 (Adobe e-Reader Format) International Standard Book Number 1-58488-348-0 (Print Edition) Library of Congress Card Number 2003069765

Dedication This book is dedicated to the memory of Lt. Robert Regan and firefighters Joseph Agnello and Peter Anthony Vega, who fell in the line of duty on September 11, 2001, rescuing people in the Marriott World Trade Center—including the author, who is forever indebted.

Acknowledgements This book would not have been completed without the assistance of the following people: David Littman, who mentored me for three critical years early in my career, and whom I consider the dean of American business economists. Ian Clemens, who first introduced me to MATLAB and who helped develop some of the routines for gravity models, sprawl, and diversificiation presented here. Ilhan Geckil and Chris Cotton, who worked with me on a number of projects excerpted here, including fiscal and economic model analyses of retail sales. Christine LeNet, who both reviewed the content in the business, tax policy, and other chapters, and formatted figures and document files for publication. Arianna Pieper and Megan Boone, who formatted, corrected, adjusted the figures, and checked the manuscript—and provided an occasional polite recommendation that I rephrase a few things. Vlad Hlasny, Dan Li, Kevin Dick, Michael Robbins, Raymond Neveu, Jay Abrams, and Ralph Sandler, who provide invaluable review comments on earlier manuscripts. Bob Stern of CRC Press, who was supportive, encouraging, and politely insistent on getting this project done. Finally, my wife, Madhu, and our children Neal, Sean, and Mohra endured many evenings, late nights, and long days without me while I labored on the text, especially the past year. It has been a long journey, but not a lonely one for an author much blessed with a wonderful family.

Table of Contents Table of Contents

ix

List of Tables

xi

List of Figures

xiii

List of Code Fragments

xvii

1 How to Use This Book

1

2 Mathematical and Simulation Models in Business Economics

16

3 MATLAB and Simulink Design Guidelines

26

4 Importing and Reporting Your Data

53

5 Library Functions for Business Economics

83

6 Economic Impact Models

110

7 Fiscal Impact Models

137

8 Tax Revenue and Tax Policy

149

9 Regional Economics

164

10 Applications for Business

182

11 Business Valuation and Damages Estimation

211

12 Applications for Finance

262

13 Modeling Location and Retail Sales

286

14 Applications for Manufacturing

331

15 Fuzzy Logic Business Applications

341

16 Bringing Analytic Power to the Internet

360

17 Graphics and Other Topics

376

Appendix A : Troubleshooting

400

Appendix B : Excel Link Debugging

405

Index

408

List of Tables Theoretical vs. Applied Economics

17

When to Use Simulation Models

24

Major Style Elements for Simulink Models

36

Styles for Specific Blocks

38

Key Simulation Parameters

42

Sample Excel Sheet for Inputting Data

62

Economic Impact of the Fantasy Game

117

Gross and Net Costs of a 25% Michigan State EITC

158

Standard Measures of Diversification

179

Concepts of Value in Accounting and Economics

215

Cost of Capital Estimates for Small Beer Distributors, 2003

242

Input Sheets for Individual Distributors

243

Questions for Audit Predictor

347

Waves of Internet Functionality

361

Actual and Visual Impression of Data

381

List of Figures Simulink Model Example: House Net Benefits

32

Costs and Rental Value Subsystem

33

Simulink Model Example: Cost Shares Subsystem

34

Simulink Model Example: Cost Subsystem

35

Top-level view of Simulink Model

37

Initialization Block in a Simulink Model

41

Linear Demand Function

91

Supply Schedule

92

Elasticity of Supply Schedule

93

Demand and Supply Graph

95

Elastic Impact Block

99

Example Business Economics Model

101

Base Income Subsystem

102

Policy Change Subsystem

102

Income and Sales Subsystem

103

Sales Projection with Policy Change

103

Fiscal and Economic Impact Model

132

Population Migration Subsystem

133

Tax Revenue Subsystem

133

Municipal Costs

143

Cost and benefit

144

Fiscal Model Schematic-I

145

Fiscal Model Schematic-II

145

Fiscal Model Schematic-III

146

Effective Tax Rates, Selected Income, and Payroll Taxes

155

Total Tax Rates on Wage Income

156

Fiscal Estimation Model

157

Gross and net costs of Michigan EITC by year

158

Selected Diversification Measures

166

Employment Risk and Reward

170

Frontier of Risk and Return

173

Sprawl Indices for Various Cities

176

Trend Projection Graphic

184

Income Statement

201

Earnings Subsystem

201

Depreciation and Amortization

201

Iterative Model: Overview

203

Iterative Model: Operating Expenses

204

Iterative Model: Tax Subsystem

204

Iterative Model: Convergence of Tax and Value Variables

205

Plausible Values from Valuation Command

249

Mortgage Analysis

265

Auto Depreciation: Double Declining Balance

267

Auto Depreciation: Half-Year Convention, Modified Accelerated Cost Recovery System (MACRS)

268

Auto Depreciation: Long-lived Vehicles

269

Return & Volatility Percent Analysis

271

Comparison of Price Changes

272

Drive-Time Analysis

300

Equal-Distance Rings

301

Sales Patterns and Distance

302

Sales Patterns and Distance: Alternative Perspective

303

Market Penetration Rate

304

Daylight Areas

305

Underlying Sales-Distance Relationship: Gravity Model

313

Estimated Sales-Distance Relationship

314

Distance-Sales Relationships for Automobile Dealers

315

Gravity vs. Polynomial Specifications

318

Xbar Chart

334

S Chart

354

Capability Chart

336

Graphical Display of Audit Predictor

350

Income Membership Functions

351

Audit Flag Membership Function

352

Surface of Rules

353

Ruleviewer for Audit Risk FIS

353

Credit Risk Simulation Model

356

3-D Graphic of Sales and Income Data

379

Proper Display of Underlying Data

380

Line Graph

384

Pie Chart

385

Bar Chart

387

Time Series Analysis

389

Growth Chart

390

List of Code Fragments A Simple Startup File

6

Display command in masked subsystem

39

Help information in masked subsystem

40

Setting parameters for blocks

40

Self-describing variable for blocks

41

Setting the Source Workspace

43

Setting Time Parameters

43

Setting Options and Simulating Model

44

Messages in a Callback

46

Character Arrays

46

Character and Cell Array Displays

47

Library Blocks

48

Master Simulation Callback

49

URLREAD for Direct Internet Data Access

60

Entering String and Numeric Data Arrays

64

Cell Arrays

65

Structure Syntax

66

Creating, Packing and Unpacking a Structure

67

Saving Structures to a .mat File

69

The Info.xml File for the Economics Toolbox

74

Creating a Valuation Data Structure

76

Simple Linear Demand Function

104

Supply Function

105

Declaring An Economics Block Library

108

Fiscal Impact Callback

146

Social Security Tax

159

Federal Income Tax Calculator

160

EITC Master M-file Code

162

Trend Projection Function

205

Trend Projection Output

206

Ito Process Projection

207

Projecting Jump Processes

208

Simulation Callback for Iterative Tax Model

208

Input List for Valuation Function

241

Valuation Session for Beer Distributors

257

Valuation of Beer Distributors Function

258

Mortgage Calculator

274

Auto Depreciation

276

Get Stocks Function

279

Test Gravity Model Output

313

An SPC Demonstration Routine

339

Audit Predictor Rules

348

Read FIS Command

357

Fuzzy Logic Audit Risk

358

Using XML to Generate Help Files

372

Info.xml file for Economics Toolbox

373

Testplot: Line Chart

390

Testplot Function

391

Testplot: Adjusting Axes

392

Testplot: Pie Chart

394

Testplot: Bar Graph

396

Testplot: Sub-Plots

398

1 How to Use This Book Organization of the Book This book is organized into chapters, each covering a topic. Sections in each of the chapters describe in more detail one aspect of the topic. Most readers will want to read a few chapters immediately and then return to cover specific topics as their interests warrant. The chapters proceed as follows: 1. The first chapter describes the organization and purpose of the book as well as how to acquire the business economics toolbox prepared by the author for readers of the book. It also provides certain maxims of business economics. Almost all readers will want to review this chapter first. 2. The second chapter contrasts business economics with academic economics and discusses why simulation models in general, and MATLAB and Simulink in particular, offer advantages to the practicing economist.1 Most readers will benefit from this chapter. 3. The third chapter describes the MATLAB and Simulink environment and provides guidelines for creating and using models in this environment. Style guidelines are presented that help make such models easier to understand and debug. 4. Chapter 4 focuses on data. We present methods to get your data into the MATLAB environment and to report it out. The chapter also contains a specific introduction to the use of Microsoft Excel as an environment for easily collecting, importing, and reporting data. Three appendices to this chapter discuss XML and structured data, creating and using custom data structures, and also importing files of various formats. Most readers will again benefit from these chapters, although those with some familiarity with the MATLAB environment will skim portions of them. 5. The fifth chapter discusses certain building blocks of economic analysis used in economics and then provides custom-programmed functions and models which implement these tools. These tools form the basis of the economics toolbox created for readers of this book. The chapter also discusses creating and using a library of such functions. This chapter introduces material not available in any other form and will be essential reading for those who wish to implement the models described later in the book. 1

MATLAB® and Simulink® are trademarks of The Mathworks, Inc., 3 Apple Hill Drive, Natick, MA 01760.

Business economics and finance

2

6. The chapters that follow describe specific fields of application: a. Economic and fiscal impact models as well as tax policy and forecasting tax revenue are covered in Chapter 6, Chapter 7, and Chapter 8. These chapters provide practitioners in these fields with advanced tools that enable more accurate, reliable analysis. The first sections of the chapter on economic impact models identify the severe weaknesses in many common economic impact reports, adding in some examples of particularly absurd gross exaggeration in published reports. These sections close with a plea for ethics in that subfield. As much of our work has been in public policy, we use these tools on a regular basis and hope that the analytical tools will help improve the level of analysis and that our admonitions about ethics in using them will not fall on deaf ears. b. Regional economics is discussed in Chapter 9, particularly the proper analysis of economic diversification for states or regions and a rigorous discussion of urban sprawl. In the first sections, we present techniques that have been recently developed and provide a much better concept of risk and return in regional economies than naive diversification analyses that are not grounded in a rigorous theory of economic growth and variation among industries. In the second section, a numerical sprawl index is presented for the first time in print. c. Chapter 10, Chapter 11, and Chapter 12 cover the economics of a firm. Chapter 10 describes modeling a firm, focusing on the crucial question of how a firm makes money. An iterative method of matching market value and expenses based on value is introduced. Chapter 11 discusses business valuation, noting the various methods used to estimate the value of a business and the various definitions of value. The chapter differs from most other references in this field in two ways: first, we concentrate on what we consider the most important consideration in the market value of a company, namely its prospects for future earnings; and, second, we utilize the greater analytical power of quantitative models that the MATLAB environment provides. d. Retail sales are discussed in Chapter 13. Much of the material presented here, including the derivation of the distance-sales relationship from microeconomic foundations, is unique to this book. Other portions provide craft knowledge of this interesting field that is rarely described in print. e. Chapter 14 briefly covers statistical process control techniques in manufacturing—a topic that is less well known than it should be among business economists and managers, given its importance. f. Fuzzy logic models are introduced in Chapter 15. Fuzzy logic is actually quite rigorous, though the name it has been given may be inhibiting its adoption as a powerful tool for incorporating various types of inf formation, including vaguely defined or subjective information, into a rigorous inference system. g. Chapter 16 deals with using MATLAB and Simulink with the Internet and includes suggestions on analytical applications on the Web, sharing and displaying information, and the use of the MATLAB Web server. This is optional reading for many readers, but it contains unique material for those who wish to advance to the state of the art for analytics and data transfer on the Web. h. The last chapter contains extensive information on the proper use of graphics to communicate data and specific MATLAB code to generate and customize a

How to use this book

3

number of charts. The chapter starts with a review of the classic rules for graphical excellence and descriptions of the all-too-common graphical errors such as “chartjunk” and distortion due to improper use of 3-D graphics. There are very few texts in the social sciences which offer guidance in the proper use of graphics, and we intend this to be one. 7. Each of these chapters describes briefly the theory behind the models and then outlines an approach. These chapters can be read, skimmed, or skipped, depending on the interest at hand. A reader dealing with a finance problem, or one interested in fuzzy logic applications, could jump right to this chapter (after, of course, reviewing the initial chapters) without necessarily reading up on economic or fiscal impact models. Numerous cross-references indicate where similar or extended material appears elsewhere in the book. 8. The appendices contain troubleshooting suggestions that could save you a lot of time and trouble.

Intended Audience This text is primarily designed for two audiences: 1. Economists, finance and valuation professionals, market researchers, public policy analysts, and other practitioners whose occupation demands the ability to model market behavior under a variety of real-world conditions 2. Teachers or students in graduate-level classes in applied economics, particularly those who cover topics such as fiscal and economic impact analysis, fuzzy logic applications, retail sales analysis, and the integration of geographic information systems, as this is one of the very few books to rigorously cover these subjects The book may also be used by those interested in specialized topics rarely covered in economics texts, such as those listed above, and by those who have extensive background in mathematical or simulation models (such as MATLAB and Simulink) and wish to extend their knowledge.

Prerequisite Knowledge We presume the reader has the following knowledge: 1. A good grounding in the laws of microeconomics and a familiarity with their application. Most practitioners and graduate students in economics, finance, public policy, and related disciplines should either be able to acquire this or should have already done so. Most undergraduates will need additional training. 2. A working understanding of mathematics, including (for some chapters) an understanding of the calculus used in comparative statistics. The completion of a graduate course in math for economists would be helpful, but is not mandatory. 3. For many of the chapters, a familiarity with (but not necessarily expertise in) the MATLAB software environment. Most of the applications presented here could be

Business economics and finance

4

accomplished in other software environments, but we provide examples of applications in MATLAB. See “References on MATLAB and Applied Economics” on page 9. 4. For some chapters, an awareness (but not necessarily a working knowledge) of geographical information systems. We suggest some resources on these topics under “References on MATLAB and Applied Economics” on page 9.

Suggested Reading Plans The organization of this book allows you to read those portions most relevant to the work you are doing at present, in particular: • Regardless of whether you are new to business economics or a veteran, read the brief “Maxims of Business Economics” on page 15. • If you are new to the use of simulation models, it is best to start at the beginning. Go through the chapters that explain the MATLAB and Simulink environment, how to get your data, and creating and using library functions. Then jump to the most interesting application chapters. • If you are focused on one type of application and have a working familiarity with MATLAB or Simulink, finish this chapter and then jump straight to the application chapters. Be prepared to review information in the earlier chapters or in the appendices. • If you are currently using MATLAB or Simulink and are looking for suggested approaches or troubleshooting information, scan the chapters on troubleshooting in the appendices, any relevant application chapters, and the early chapters on design guidelines, getting your data, and library functions. • If you want to learn about using MATLAB and Simulink on the Internet, jump to that chapter but be prepared to refer to other areas.

Typographic Conventions We have adopted certain typographic conventions that will assist the reader in understanding the text, such as: • The main text of the book is written in a normal font, like this. • Text that is part of a computer program or is a command you type in a software environment is in a keystroke font. • Program commands for software that uses menus are sometimes summarized by listing the menu selections that execute them with the piping separator (“|”) between the menu selections. For example, to use the MATLAB menu command to open a new Simulink model, you would execute the following menu items: 1. First, hit the File menu with your mouse or with a keyboard command (such as AltF).

How to use this book

5

2. Second, hit the New submenu command on the File menu. 3. Third, select Model from the File submenu. We summarize this set of commands as: File|New|Model. Changing Software Commands Keep in mind that software companies change the menus in their products frequently, and you may need to use a different set of commands if you are using a different version of the software or on a different operating system. Also, there may be a shortcut method using a combination of keystrokes or mouse actions that can accomplish the same operation in a different way. MATLAB Programming and Code We have provided the actual code for a number of MATLAB programs we have prepared to illustrate the techniques described in this book. Longer sections are listed as the code fragment “A Simple Startup File” on page 7.2 We call these code fragments because they are written in a specific software language or code, and because many of the longer code sections are shortened, the code included in this text may be only a portion or fragment of the entire file. Main Purpose of Code Experienced MATLAB users will undoubtedly notice ways in which the execution of these programs could be speeded up or different ways of accomplishing the same thing. The primary purpose of including the programs is to demonstrate how to perform certain tasks and not to execute those tasks with maximum efficiency. Therefore, you will note that many of the programs include extensive comment lines (which begin with a percentsign [%] mark) that are ignored by the computer. If you are reviewing these code fragments in order to perform a similar task, pay attention to these comment lines. Those who can recommend a more efficient—or more effective—code to accomplish the same result are encouraged to send a note to the author. See the contact information at “Contacting the Author” on page 9. Version Notes The versions of MATLAB used during the development of this book included R11, R12, R13, and a prereleased version of R14. We believe that all of the routines will run, in some cases with minor modifications, on R12 and R13. Most will run on R11 as well. Based on our testing of the comparison business economics toolbox with the prereleased version of R14, we anticipate that all of the routines included here will also work under 2

A startup file is a set of instructions run by MATLAB when the program is first run. We recommend that users customize their startup files; this is discussed in Chapter 3, this book, under “Setting Up the MATLAB Workspace” on page 30.

Business economics and finance

6

R14, perhaps with minor modifications. Users should expect that different versions will have some interface differences as well. Code Fragment 1-1. A Simple Startup File

% Startup file for Patrick Anderson % Place in MATLABroot\work directory % % --- Change directory to folder with Matlab models CD P: \models; % % ---Messages-message = [ 'Good afternoon, Mr. Anderson. God bless you and your work' ]; disp (message); % % ---Show version-ver;

Accessing Files and Online Resources Many of the MATLAB program files described in this book, including script and function m-files, and Simulink models, are available online from the author or publisher. Other information about the content of the book, including corrections of any errors, may also be posted. We hope this book will be used for years. Note that Web sites tend to have short life spans, at least at the same Internet address (known as a universal resource locator or URL). Therefore, we are providing you with a set of Internet addresses to examine in the hope that several years from the publication date you can access the information prepared for readers of this book.

Accessing the Economics Toolbox The author has prepared a business economics toolbox containing many of the MATLAB functions, scripts, and Simulink model files described in this book. It is the author’s intention to offer this toolbox to bona fide purchasers of this book as an additional, licensed software product. The license for the product allows purchasers of this book to download and use the toolbox free of charge subject to the conditions stated below:

How to use this book

7

Disclaimers and Limitations It is unfortunate, but our litigious society requires even those that provide products free to outline certain limitations and disclaimers, which we do below: • While it is the author’s intention to provide the business economics toolbox, we do not guarantee that the files will be available indefinitely, that they will work on specific computer platforms, or that a fee will not be charged for a license at some future date. • The author may require the endorsement or acceptance of a license as a condition for providing the toolbox and to make further restrictions, including restrictions on reproduction or resale. • Acquiring a license for the toolbox does not entitle a reader to a license for MATLAB, and vice versa. • Neither purchase of the book nor downloading the toolbox qualifies the reader for technical assistance or help of any kind. • Any downloaded files are provided with no warranty, including no warranty of fitness or merchantability. Users assume all risks of use. • The author may provide the toolbox in compressed format, require verification of book purchase, charge an additional fee to unlock the code, or rely on an intermediary (such as the publisher or The MathWorks) to provide the toolbox.

Contacting the Author and Publisher Readers should periodically check the following Web sites for related resources and the companion economics toolbox. Contacting the Author Patrick L.Anderson is a principal in the consulting firm of Anderson Economic Group headquartered in East Lansing, MI. The firm maintains a number of Web sites, including http://www.andersoneconomicgroup.com. A set of pages on this site is devoted to this book, and it is our intention to post any revision notes, related works, resources, errata, and other information on those pages. If you have a suggestion about a topic to be covered in a future edition, an observation on a better approach to some problem, or you have discovered a typographical or conceptual error, please contact us via e-mail or regular mail. Check the Web site for current mailing and e-mail addresses. Contacting the Publisher CRC Press maintains an active Web site, which includes downloadable files and other information for many of its titles. The current address is http://www.crcpress.com.

Business economics and finance

8

Contacting The MathWorks The MathWorks maintains an active Web site which includes a file exchange area, product information, technical notes, and other support information. The current address is http://www.MathWorks.com.

References on MATLAB and Applied Economics This book is about applying economic principles to practical problems in business, finance, public policy, and other fields. The principles themselves are timeless; the applications described in this book can be done in a number of software environments. Indeed, the first principle we recommend—important enough that we call it a maxim—is to think through the problem before trying to restate it in mathematical terms.3 However, once you have thought through the problem, you will normally have to describe it in mathematical terms and do so in a software environment that allows you to complete the calculations, simulations, reporting, and graphical illustrations that are necessary. We describe in a later section the advantages and disadvantages of different categories of software that can accomplish some or all of these tasks.4 In this book, we provide detailed descriptions of analysis in three of these environments: mathematical and simulation models (MATLAB and Simulink), Geographic Information Systems (GIS), and spreadsheets (particularly Microsoft Excel). This book, however, does not provide a tutorial for these software programs. Therefore, we provide below suggestions for those readers who would benefit from additional information on the software products described in this book. Suggested Resources for MATLAB Users in Business, Economics, and Finance The following resources are recommended: 1. New users of MATLAB will probably benefit from one or more of the general reference books or booklets listed below in “General Books on Using MATLAB.” These will not provide application advice though, and most examples in them are from other fields. 2. Within this book we introduce a number of basic and many advanced MATLAB techniques that are quite helpful in business, economics, and finance. A chapter-bychapter summary of these is in “MATLAB Explanations in this Book” on page 11. 3. Those with a rudimentary knowledge of MATLAB can simply read the book in one of the ways suggested in “Suggested Reading Plans” on page 5 and determine whether any of the references listed in the chapters are necessary for their work. 3

“Think first—calculate later.” See “Maxims of Business Economics” on page 15.

General Books on Using MATLAB • A Primer on MATLAB, 6th ed., by Kermit Sigmon and Timothy Davis, CRC Press, Boca Raton, FL, 1994. This is a very thin, almost vestpocket reference on the basic MATLAB commands, syntax, and other essentials. • Mastering MATLAB 6 by Duane Hanselman and Bruce Littlefield, Prentice Hall, Upper Saddle River, NJ, 2001. Subtitled accurately as “A Comprehensive Tutorial and Reference.” The authors also provide, for a nominal charge, a related set of utility programs.5 4

See Chapter 2, this book, under “Software Environments” on page 21 and under “Limitations of Spreadsheet Models” on page 23. 5 We describe one in Chapter 4, this book, under “A Shortcut Utility” on page 78.

• Graphics and GUIs with MATLAB, 3rd. ed., by Patrick Marchand and O.Thomas Holland, Chapman & Hall/CRC Press, Boca Raton, FL, 2003. This comprehensive book provides extensive information on creating graphics in MATLAB. Handle Graphics is one of the most powerful features in MATLAB. We provide examples of graphics routines that are designed for users of this book in Chapter 17, “Graphics and Other Topics,” but more advanced users will want a reference book on graphics, and we recommend this one. • MATLAB User Guides and other documentation distributed by The MathWorks with the MATLAB software. Many publishers of software programs provide little or no documentation or provide poorly written guides that must be supplemented by additional purchases.6 Fortunately, The MathWorks provides extensive references that are, by and large, well written and authoritative. This should typically be the first place a user goes for explanation and guidance on using the program.7 However, most of these references (with a few notable exceptions) are not intended for practitioners in economics, business, or related fields, and such individuals will often benefit from additional information in books such as this that focus on their fields of interest. MATLAB Explanations in This Book While this book is not an introduction to MATLAB, the following sections provide, in

Business economics and finance

10

7

Users can get guidance from: (1) within the command window, the Help function for all commands (e.g., typing Help Print will produce information on the Print command); (2) the help pages available from the desktop; and (3) the extensive technical notes and other information available on the MathWorks Web site which is at: http://www.MathWorks.com.

• Chapter 5, “Library Functions for Business Economics,” reviews fundamental tools of economic theory and shows how to create MATLAB tools that apply those tools to practical problems. Specialized functions useful to business, economics, and finance are presented, including supply and demand calculations and special Simulink blocks for constant growth, varying growth, and elastic impact. • Chapter 6, “Economic Impact Models,” and Chapter 7, “Fiscal Impact Models,” present Simulink models for these tasks. • Chapter 8, “Tax Revenue and Tax Policy,” describes functions that model the U.S. income tax, U.S. payroll taxes, and other taxes. • Chapter 9, “Regional Economics,” provides mathematical tools for analyzing regional economies, including newly developed methods for calculating the diversification (risk and reward characteristics) of regional economies and their recession severity risk. • Chapter 10, “Applications for Business,” includes a useful projection function, as well as a general business model and an iterative tax and market value simulation model. • Chapter 11, “Business Valuation and Damages Estimation,” uses custom data structures and functions for different valuation formulas to estimate values using multiple methods. • Chapter 12, “Application for Finance,” introduces the many MATLAB capabilities for financial modeling and includes a special GetStocks function that acquires data from an Internet provider, analyzes it using special operations used in finance, and then graphs it. • Chapter 13, “Modeling Location and Retail Sales,” explains a number of rarely documented methods to model retail sales, including gravity models. We present functions to perform distance-sales analyses and introduce optimization as a method within MATLAB to estimate parameters for models that are nonlinear. • Chapter 14, “Applications for Manufacturing,” provides an overview of an important topic barely understood outside engineering circles—statistical process control (SPC). Some fairly simple SPC functions are presented along with a few suggestions for understanding this important field. • Chapter 15, “Fuzzy Logic Business Application,” provides a brief introduction to this burgeoning field which is sometimes called artificial intelligence or expert systems. A fuzzy logic income tax audit predictor is presented, which was run on the Internet (via a MATLAB Web server) for more than a year, encompassing two April 15 filing dates. A credit risk simulation model is also presented in this chapter. • Chapter 16, “Bringing Analytic Power to the Internet,” begins with a sober reflection on the relatively primitive amount of actual analytical power provided by most Web sites. It then describes how the use of a MATLAB Web server can significantly increase the ability to provide advanced analytics to a remote user. • Chapter 17, “Graphics and Other Topics,” is devoted entirely to the proper use of graphics. It provides examples showing how to generate test data, draw all the major

How to use this book

11

type of graphs, customize them with different scale, annotation, and other features, and identify them for future use. • Appendix A: “Troubleshooting,” provides general MATLAB troubleshooting. • Appendix B: “Excel Link Debugging,” focuses on this useful but troublesome connection and how to make it work. Books on Applying MATLAB for Business, Economics, and Related Fields We are not aware of any other book that describes how to apply MATLAB to general business economics and finance problems.8 However, there are many texts that focus on specific fields within or overlapping those discussed in this book. Those we recommend are: • Our book starts with a perspective similar to the book Handbook with MATLAB8a with an application of social science principles to real-world problems. As such, this book describes a number of statistical techniques (such as the bootstrap) that are particularly applicable to real-world problems. The comparison of academic and computational statistics was the model for our comparison in Chapter 2, under “Business Economics vs. Academic Economics” on page 19. • “Macro-Investment Analysis,” an “electronic work-in-progress” by William F.Sharpe,9 winner of a Nobel Prize in economics,9a was 8

The author would be happy to be informed of new texts or older texts that escaped his knowledge; see “Contacting the Author” on page 9. 8a Computational Statistics Handbook with MATLAB by Wendy Martinez and Angel Martinez, CRC Press, Boca Raton, FL, 2001. 9 It can be found at: http://www.stanford.edu/~wfsharpe/mia/mia.htm. See also the references in Chapter 12 in this book, “Applications for Finance,” in the sections noted. 9a William Sharpe, Harry Markowitz, and Merton Miller won the Noble Prize in Economics in 1990 for their pioneering work in finance.

one of the creators of the mean-variance framework for analyzing investment portfolios. We describe applications of mean-variance analysis of investment portfolios in Chapter 12, this book, under “Investment Portfolio Analysis” on page 303. • The books by Paolo Brandimarte and Neil Chriss on the analysis of options and other derivative securities using MATLAB are listed in Chapter 12, “Applications for Finance.” • Applied Computational Economics and Finance by Mario Miranda and Paul Fackler, MIT Press, Cambridge, MA, 2002. This book describes numerical methods and the mathematics behind them in depth and provides a number of application examples using MATLAB, custom-programmed optimization, and other routines. Where other published works have been used in a significant way to prepare this text, we have cited them in the section describing the application. We also provide citations for reference texts covering the fundamentals of certain techniques.

Business economics and finance

12

Fundamental and Historical References Finally, we have made a special effort to cite those who pioneered certain techniques or who originated important ideas that are now incorporated into the mainstream. These individuals and their contributions are too often neglected in contemporary works, especially those that are focused on software programs. Such neglect not only robs these individuals of the recognition they deserve, it also breeds a group of practitioners that lacks the knowledge of why, how, and under what conditions a certain approach works well.10 Albeit briefly, we describe the foundations in most chapters. Books for Other Fields Those interested in applying MATLAB in other fields will often find multiple texts on specific applications. There are over 300 published books on using MATLAB in fields such as engineering, signal processing, mathematics, numerical methods, finite analysis, radar, communications, control systems, neural networks, mechanics, filters, earth sciences, electronics, statistics, and probability. This extensive library is one of the advantages of using MATLAB as a software environment. The MathWorks web site lists many of these books by category. 10

“Those that cannot remember the past are condemned to repeat it,” George Santayana’s observation, is a broad statement about the human condition. In a narrower sense, those that cannot remember why a certain method was developed in the past are likely to misuse it in the future.

Maxims of Business Economics Economists learn a lot through detailed academic work and then receive additional practical training. When prompted about their training, I have noted that professionals early in their career recite specific academic classes as well as opportunities to learn skills. The same question, put to successful business people later in their careers, often produces a surprisingly different set of lessons that has enabled them to succeed. Most of the remainder of this book is devoted to skills in applying business economics, including quantitative techniques, analytical techniques, and presentation techniques, as well as methodological notes and cautions. In this section, however, we summarize a set of maxims that will enable economists to be successful in their careers regardless of how much math they know. With that said, here are six maxims for business economics: 1. Remember—it is a social science. There is a joke that “an economist is someone who looks at reality and wonders whether it would work in theory.” Like most jokes, there is a kernel of truth in that observation. Economics models human behavior. Economics applied to real-world situations, the focus of this book, models human behavior when such humans are placed in common situations. Applying economic thinking to actual human behavior forces one to confront the untidy, unexpected, and occasionally unexplainable behavior of fellow members of

How to use this book

13

one’s species. Thus, the first maxim is to remember that economics is a social science, by which we mean economics only works when it models human behavior. The corollary to this is: when human beings do not behave like the model, it is probably the model that is wrong. 2. All economics is microeconomics. All social science is an attempt to explain the behavior of individuals. Of course, the aggregate of those individual behaviors is the behavior of groups, including groups of consumers, producers, taxpayers, government officials, and other groups that are important to a business economist. However, when tempted to describe macroeconomic behavior that is at odds with the microeconomic foundation for individual behavior, remember this maxim: if it does not work at the microeconomic level, it will not work at the macroeconomic level. Recent pioneers in economics, including at least a few winners of the Nobel Prize, have documented failures of macroeconomics that stem directly from violation of this maxim.11 Robert Lucas summarized one set of such errors, in macroeconomics as follows: The prevailing strategy for macroeconomic modeling in the early 1960s held that the individual or sectoral models arising out of this intertemporal theorizing could then simply be combined to form a single model, the way Keynes, Tinbergen, and their successors assembled a consumption function, an investment function, and so on into a model of an entire economy. But models of individual decisions over time necessarily involve expected future prices. Some microeconomic analyses treated these prices as known; others imputed adaptive forecasting rules to maximizing firms and households. However it was done, the “church supper” models assembled from such individual 11

The Nobel Prize winners that spring to mind include the following four: Milton Friedman’s pioneering work on monetary policy illustrated how failures in government policy, primarily monetary policy, induced individuals to behavior that deepened the Great Depression. His work on income and consumption in the late 1950s is a classic demolition of the use of macroeconomic data alone to model the behavior of individual consumers, and it established “permanent income” as the basis for sound thinking about consumption patterns ever since. Robert Lucas, who pioneered modern “rational expectations” theory, demonstrated how traditional Keynesian economics was frequently at odds with individual incentives and, therefore, wrongly predicted how an economy would react to policy changes. It is interesting to note that one of the first applications of what became known as “rational expectations” theory was by John Muth in 1961, explaining how to model consumption, given Friedman’s “permanent income” theory. James Buchanan, who pioneered modern public choice theory, demonstrated that government officials and interest groups behave like normal, rational individual economic actors. James Heckman focused his 2000 Nobel Prize Lecture on the importance of microdata and the tools within microeconometrics to deal with heterogeneity in the population. See New Palgrave Dictionary of Economics, various entries; Nobel e-Museum at http://www.nobel.se; J.Muth, “Rational expectations and the theory of price movements,” Econometrica, 29, 315–35, 1961; M.Friedman and A.Schwarz, A Monetary History of the United States, 1867–1960 (Princeton, NJ: NBER, 1963); M.Friedman, A Theory of the Consumption Function (Princeton, NJ: Princeton University Press, 1957).

Business economics and finance

14

components implied behavior of actual equilibrium prices and incomes that bore no relation to, and were in general grossly inconsistent with, the price expectations that the theory imputed to individual agents.12 Going back to the times before Alfred Nobel, pioneers of economics such as Adam Smith, David Ricardo, and others grounded their economic arguments on the behavior of individuals. Modern pioneers of business similarly achieve wealth and influence by providing products that individuals (persons and companies) want to buy and not by providing products that on average, or in aggregate, the economy as a whole will want to buy.13 While your goal may or may not be winning 12

Lucas, Nobel Prize Lecture, December 1995; found at: http://www.nobel.se. I should add, at this point, the political economy corollary of this maxim: “All politics is local.” Attributed to the former Speaker of the U.S. House of Representatives Thomas O’Neill, this corollary is part of the underlying knowledge about human behavior from which springs the study of political economy. 13

the Nobel Prize, you can certainly succeed much faster by remembering this maxim. 3. Think first—calculate later. Many highly technical, mathematically intense, and impressive-looking economic analyses are completely worthless because the author did not think through the problem before producing his or her equations. The proliferation of software, including spreadsheets, statistical packages, and simulation software such as MATLAB, greatly expands the power of the economist to model behavior and provide detailed, multiperiod forecasts or analyses. Power, however, can be misused. Simply because one can extrapolate for another 10 years and produce a nice chart, does not mean the exercise is useful. A recurring theme in this book is the importance of thinking first before rushing to create a complicated model. I should also note the academic corollary to this maxim: think first—differentiate later. 4. Know your data. This is an area where business economics is quite different from theoretical economics. Analysts should always spend time understanding the source, reliability, meaning, and deficiencies in the data. Most data have some deficiencies. Some data are produced by parties with an interest that should be understood before pasting the data into an equation. Be sure that you always know your data. 5. Be ethical. There are many opportunities in the world of academic and business economics to cut ethical corners in an attempt to produce a more sensational analysis, masquerade someone else’s work as your own, or simply toot your own horn inappropriately. No book by a human author can reform this essentially human deficiency. However, if you

How to use this book

15

do not recognize a standard, you will certainly not follow it. Therefore, establish an ethical standard in your work and discipline yourself and your coworkers to follow it. 6. Be humble. The best thinkers start off by knowing what they do not know and admitting it. If you are reading this book, you are, in all likelihood, an intelligent person who either now or in the future will be considered an expert on some topics. Resist the temptation to claim expertise in an area in which you are an intellectual bystander. In your own field, be careful to cite the contributions of others and to identify the bases of your assumptions, the sources of your data, and the limitations of your knowledge and experience.

Conclusion These maxims could be applied in many fields. I hope the remainder of this book imparts a great deal of practical knowledge about modeling economic behavior, and that both author and reader follow these simple maxims.

2 Mathematical and Simulation Models in Business Economics Business Economics vs. Academic Economics Economics is a social science. It seeks to describe the incentives operating on individuals as they work, save, invest, contribute, vote, and consume. Like any field of science, economics can be studied at the widest theoretical level, at a minute practical level, and at any point in between. This book looks at the practical applications of economic reasoning, using techniques that are based in rigorous theory and proven in actual practice. We entitle the book Business Economics and Finance because the majority of the applications focus on individuals in business dealings. However, there are many topics that f ocus on government organizations and their interaction with individual workers, managers, and consumers. It is worth pausing to review how this practical, applied economics differs from the theoretical economics that is taught in colleges and universities today. While there is plenty of cross-over among the subdisciplines, and most economists devote some of their time to both, it is worth considering the differences. Table 2-1, “Theoretical vs. Applied Economics,” highlights some of the important characteristics of both.14 Why Practice Business Economics? As Table 2-1 indicates, academic economics normally deals in a smoother world in which data are available or easily assumed, model structures are specified often without argument, and rigorous statistical inferences are common practice. Why, then, practice applied economics with its messy or difficult-to-obtain data, lack of specification of models, and stricter budget constraints? The answer to that question is much like the answer to the question “Why climb the mountain?” Because it is there! There are a huge number of practical questions facing individuals, their employers, their governments, and the 14

This comparison is inspired by a similar one prepared by W.L.Martinez and A.R.Martinez in Handbook of Computational Statistics (Boca Raton, FL: CRC Press, 2002), in which they compare academic statistics with computational statistics.

Mathematical and simulation models in business economics

17

stores and service providers that sell to them. These questions normally cannot be solved with theoretical economics alone; they must be approached with applied economics. This book deals with applied economics and shows how advanced use of mathematical and simulation software can help answer the tough, messy, and immediate challenges of today. Why Study Academic Economics? The challenge of practical business economics should not dissuade one from learning in an academic setting. Many, though not all, of the techniques

TABLE 2-1 Theoretical vs. Applied Economics Characteristic

Theoretical Economics

Applied Economics

Data

Usually assumed to exist in exactly the right periodicity

Must be acquired, often with significant effort; will contain errors, breaks, and different periodicities

Data sources

Data are assumed to exist; unobservable variables may be used in equations

Desired data often do not exist. Observed data must be used from private, government, and nonprofit organizations, and experiments

Analysis

Simple to complex algorithms; often developing theory using mathematics

Simple to complex algorithms; often testing applications of existing theory using statistics

Questions

Can be posed by researcher, based on interest; abstraction allows for intense focus on specific questions

Usually posed by events beyond the control of the researcher; often multiple questions are posed

Time and budget constraints

Time constraints are largely based on academic calendar; academic budgets include time for pure research

Time constraints are largely based on events; budget constraints established by clients

Inference practices for parameters

Rigorous statistical inference, given strong assumptions and assumed data

Practical limitations, given potential for specification error and data problems

Assumptions about Strong, often unverified data and error process assumptions regarding data and errors; error processes often assumed to be clean

Relatively few assumptions about data and errors; error processes often messy

Knowledge of underlying structure

Often strong assumptions about underlying structure, based on theory

Structure may be unclear, or is typically inferred from actual behavior

Key focus of specification

Optimal analysis

Robust analysis

Business economics and finance

Importance of location and geography

Often ignored or assumed away

18

Normally quite important and may be the focus of inquiry

described in this book originated in academic settings. Even the mountain climber who climbs mountains because they are there probably went to a mountain-climbing school. This book borrows some techniques of academic economics in laying out data and sources, giving proper credit to those that have developed or written about a problem before, and in conveying information to others interested in this field. While practical problems require practical solutions, one should still remain true to the essential philosophies of social science.

Why Use Mathematical and Simulation Software? Given some data and a set of equations that summarize a particular market, an economist will normally use some type of computer software to collect the data, display it, and calculate equations using it. There are many types of software available today that allow for automatic calculations of a series of equations. Each has its intended purpose and is normally quite good for that purpose. Before describing how a true simulation modeling environment can be used to great advantage, let us review the categories of software that can be used in applied economics. Software Environments The following illustrative list of software environments includes specific products as well as their intended purposes:15 • Spreadsheet software such as Microsoft Excel, Quattro Pro, Star Office, etc.: The design of these packages renders them particularly useful for typical accounting tasks, and their feature set can be extended to include various statistical and financial functions. • Statistical software, including SAS, SPSS, Minitab, Stata, Splus, etc.: These are designed primarily to estimate parameters for equations, given a structure and data.16 15

Various products mentioned here are trademarked or copyrighted by their respective owners. The list is illustrative rather than exhaustive. Many readers will know of other examples, including examples available under the GNU public license and shareware or freeware licenses. 16 These packages normally allow for “nonparametric” statistical tests. However, even nonparametric statistics typically require an assumed model structure, even if it is only assuming that one event causes another. By contrast, we consider “time series” methods (including ARIMA and VAR methods) as “nonstructural” because they do not require the specification of an underlying model structure.

• Econometric software, including RATS, TSP, Shazam, Eviews, etc.: They are similar to statistical software but are designed around time-series economic data.

Mathematical and simulation models in business economics

19

• Geographic information systems (GIS) such as MapInfo, ArcView, TransCAD, Maptitude, the mapping toolbox for MATLAB and free or open-source software such as Geode and GRASS: These software environments allow analysis to include spatial variables. A feature of this book is the explicit inclusion of geographic information in the analysis. • Mathematical software, including MATLAB, Octave, Maple, Gauss, and Mathematica: These contain an enormous reservoir of mathematical routines and can be programmed to produce virtually any function or graphic. • True simulation models: These incorporate systems of dynamic equations that can be solved iteratively over multiple periods. These include custom-programmed models in specific fields,17 certain applications of mathematical, statistical, and econometric software (including some listed above), and the Simulink software developed by The MathWorks, which is based on MATLAB.18 Simulation Models vs. Spreadsheets Spreadsheets are probably the most common analytical program used in business economics. Spreadsheets have powerful advantages, including low costs, intuitive use, and an ability to easily print the data used in its calculations. For most accounting work and many other uses (including uses we will describe in later chapters), you cannot beat a spreadsheet package. However, for analytical work requiring dynamic interaction among variables— meaning that one variable affects another, which affects two more, and the latter affects the results of the next-period variables—spreadsheets fall far behind. Although you can “trick” a spreadsheet into performing some advanced analysis and even limited dynamic equations, such uses are beyond their intended scope.19 17

For example, the rainfall-runoff TOPMODEL first developed in 1979 and written in Fortran (found at http://www.es.lancs.ac.uk/hfdg/topmodel.html); Agricultural Non-Point Source (AGNPS), developed by the USDA Agricultural Research Service to predict soil erosion and nutrient transport within agricultural watersheds and written in C (found at: http://www.geog.unihannover.de/phygeo/grass/agnps.html): and numerous others, particularly in electronic devices and software design. 18 MATLAB® and Simulink® are trademarks of The MathWorks, Inc., which can be found at http://www.MathWorks.com. 19 For example, some years ago the author created a multiperiod model of the educational market, which was used to forecast the migration of students to private schools should a school-choice program involving those schools be approved by voters in a large industrial state. The

Business economics and finance

20

Limitations of Spreadsheet Models Spreadsheet software has serious limitations as an analytical tool. These limitations include: 1. A spreadsheet is inherently a two-dimensional device. Many problems can be solved in a 2-D environment, including almost all accounting problems. Indeed, spreadsheet is a term borrowed from accounting. However, most problems in business are not twodimensional. 2. While spreadsheets easily display the data used for calculations, they do not easily display the formulas used to calculate that data. If all the calculations are simple additions and the proper formatting is applied, this limitation is largely overcome. However, when anything more complex than simple addition or subtraction occurs, spreadsheets often obscure the calculations.20 3. Most problems involving multiple variables that interact with each other over time cannot be modeled correctly using a spreadsheet.21 Even if the analyst creates multiple worksheets showing different scenarios in an attempt to overcome the 2-D limitations of the spreadsheet itself, the number of potential scenarios overwhelms the ability of the software to calculate and then express the results. With two dimensions, a spreadsheet can typically handle either a small set of variables over time, or a large set of variables at one time—but not both. The sheer size of a spreadsheet model model, implemented in Microsoft Excel, took nearly a dozen individual spreadsheets, each with many columns, to project the fiscal impact. The modeling task took at least a month. Explaining how it was done took many pages in the resulting report. More recently, using the tools and skills explained in this book, a similar project was completed in half the time with more accuracy. See Patrick L.Anderson et al., The Universal Tuition Tax Credit, Midland, MI: The Mackinac Center, 1998; available at http://www.mackinac.org. 20 Even multiplication is difficult to show adequately. For example, consider how taxes are shown on accounting statements. Unless the tax is a straightforward multiple (such as a flatrate sales tax), the tax liability is normally shown without providing the reader the ability to review the tax rate, base, or calculations. Of course, it is possible to see the formulas in a spreadsheet, but the variables used are typically cell reference, and a special command or set of keystrokes is often required to reveal the formulas used to generate results in each cell of a spreadsheet. 21 It is possible to display the results of one scenario involving multiple, interactive variables over more than one time period. This is what accounting statements for a firm provide. However, if you look at a set of income statements and balance sheets for a corporation and ask “What if sales were higher, commissions lower, and personnel costs sharply reduced,” you run immediately into the limitations of a 2-D environment. Although you could display this alternate scenario, the environment itself would not keep track of the relationships among these variables or allow an efficient manner of generating a large number of alternate scenarios involving true interactivity among the variables.

Mathematical and simulation models in business economics

21

necessary to model a multiperiod, multivariable problem can be overwhelming.22 4. Although not a defect in the software itself, the widespread use of spreadsheets induces an intellectual laziness regarding how variables interact together. It is much too easy to look at a column of numbers, notice that they add up correctly and then conclude that the number at the bottom of the column must be correct. Comparison with Simulation Models Consider how a true simulation modeling environment, such as MATLAB or Simulink, overcomes some of the limitations of spreadsheet models: 1. A simulation model is n-dimensional. You can include as many variables as you think are important and relate them in multiple ways. You are not restricted to thinking in rows and columns. 2. An enormous variety and number of operators and functions can be used in simulation models. Furthermore, these operators and functions are clearly visible when creating the model, rather than being buried underneath a cell in a spreadsheet. This allows—in fact, requires—you to specify exactly how variables interact. 3. Simulation models are designed to handle a large number of variables which interact and change over time. Such an environment can therefore model more effectively the actual workings of markets with many participants. 4. Using a simulation model environment forces the analyst to explicitly identify the variables, and describe their interaction over time. Indeed, part of the relative difficulty in using the environment is the requirement to explicitly describe all these factors in a manner that is absolutely consistent. While within a spreadsheet environment you can easily mix apples with oranges, it is more difficult to do so within MATLAB.23 While you can make errors using simulation models, gross specification errors are less likely. 22

As an illustration, note the size of the spreadsheets used to forecast business income statements. It is not uncommon for these to be 10 columns wide by 40 rows long, and many are much larger. Even allowing for half of the cells to be used for formatting, notes, or white space, that is 200 actual data cells. Each cell, in turn, has either data input or a formula, and one can only infer what that is from the context. 23 For example, a common error in spreadsheet environments is mixing balance sheet items (which are stocks) with income statement variables (which are flows). It is quite easy to, for example, add expenses to assets to produce a bogus concept that, nonetheless, is added up correctly. If you attempt to do this within MATLAB or Simulink, you may receive error messages, as the matrix dimensions may not match. Remember that in a spreadsheet, if you can put numbers in a column, the program will add them up!

Business economics and finance

22

Why Use MATLAB and Simulink? Once you step beyond spreadsheets and statistical software, the available choices dwindle. In our experience, mathematical modeling software provides enormous advantages to those who must model real-world markets. Using MATLAB We have found that MATLAB and its companion simulation software, Simulink, offer unparalleled power, reliability, transparency, and flexibility to analyze complex economic phenomena and graphically display the results, as described below: Power: The ability to use almost every mathematical technique now in use and custom-program many more gives the MATLAB user extraordinary capabilities. Reliability: MATLAB code is close to a high-level computer language such as C. It therefore does not have the undocumented features that are common in operating systems and popular office software, particularly the versions that are designed for home or light office use on Microsoft Windows platforms. Transparency: All MATLAB functions, formulas, and data can be accessed by the experienced user. This means there should be no “black box” calculations. Even intermediate and temporary data in the midst of being calculated in a function file can be viewed through the debugger. Flexibility: MATLAB was not originally designed for economics—but then, it was not originally designed for the many fields in which it is now used. However, the building-block nature of the commands allows a savvy user to create almost any conceivable application. Using Simulink In addition to the advantages of MATLAB, there are additional advantages in using Simulink for economists, business analysts, and others interested in solving problems in economics, finance, public policy, and business. They are as follows: 1. Many economic questions are better answered with a simulation model than simply guessing, attempting to construct an analytical example, or using spreadsheets to mimic part of the underlying process. 2. The entire environment allows for rigorous, exact, multiperiod calculations using a very large array of mathematical calculations. 3. The Simulink environment allows for the model to be built and displayed graphically, enabling a user to see directly how each variable affects another. While the graphical approach is equivalent to sets of equations (indeed, it is a set of equations), the model schematics are often easier to understand.

Mathematical and simulation models in business economics

23

4. Extensive graphical and diagnostic tools are available for reviewing and reporting on the model and the data. 5. Given the model’s graphical output, the methodology can be presented in a transparent manner, allowing reviewers to assess directly and independently how the results were obtained, what data were used, and how the calculations were performed. 6. The environment is designed as a true simulation model and includes parameters, algorithms, and a software interface designed for that purpose. Drawbacks of MATLAB and Simulink In the impressive list of attributes above, there are two notable absences: “easy to use” and “inexpensive to acquire.” However, economics is about trade-offs. Through this book and others recommended here, we can help the interested reader quickly use MATLAB to perform advanced analyses and create impressive graphics. It is still harder to perform simple calculations in MATLAB than it is to perform the same tasks in a spreadsheet. It is sometimes harder to perform rudimentary analysis (such as a present value, straightforward financial statement analysis, or exploratory data analysis) in MATLAB than in other software. Reporting results, especially of simple calculations, also takes more work. However, the power and other advantages have convinced us that the environment is the best available for many uses in demanding analytical tasks such as those presented in economics, finance, public policy, and business.

Business economics and finance

24

When To Use Mathematical or Simulation Models Table 2-2, “When to Use Simulation Models,” summarizes our advice on when to use simulation modeling, spreadsheet, and statistical or mathematical software. When To Use GIS and Database Software We integrate the use of GIS in business economics problems in which location is a major factor. Although neglected in the economics literature for the past

TABLE 2-2 When To Use Simulation Models Task

Add up columns of numbers, such as in most accounting tasks

Spreadsheet Software

Mathematical or Statistical Software

Simulation Modeling Software

Recommended

Calculate discounts, simple Recommended (for Recommended (for multiplication and division of one- or two-period multiple-period multiple numbers analyses) analyses) Test out various specifications of a model, given the data

Recommended, Possible use, especially if statistical especially when inference is required specification is complicated

Project variables many periods into the future

Recommended (for simple models)

Considering multiple scenarios, given a model with interaction among variables and changes in a handful of variables

Recommended (for simple and complex models) Recommended

century, location is an essential—and sometimes primary—element of many problems in business economics. We describe explicitly the use of GIS in this book in a few instances. However, for many other applications, we incorporate spatial analysis without explicitly describing the use of GIS. We encourage the reader to consider how detailed information on location, distance, proximity, and other spatial characteristics affect the analysis. In many cases, GIS can assist the user in quantifying the effects of these variables. Similarly, we describe the importance and acquisition of data in several sections of this book. For many users, relational databases will be of great use in storing and retrieving the data. For others, the time and expense necessary to use such software will be prohibitive, and other methods will be more than adequate.

Mathematical and simulation models in business economics

25

An Admonition Using a true mathematical modeling environment overcomes the limitations of spreadsheet models and allows much more powerful analysis. However, you can make errors using MATLAB just as you can using Excel. Therefore, we offer the following warnings to users of mathematical and simulation models: 1. Document your models and analysis. This helps to avoid making errors in the first place and improves your ability to catch them in the future. We suggest methods of doing so in Chapter 3, “MATLAB and Simulink Design Guidelines,” and in Chapter 4, “Importing and Reporting Your Data,” as well as in other chapters. 2. Use style guidelines. In this way, it is easier to understand the structure of models— either the ones recommended in this book or the ones you develop yourself. We devote Chapter 3, “MATLAB and Simulink Design Guidelines,” to this topic 3. Build models so that they report intermediate results and maintain data consistency. “Garbage in, garbage out” applies to the most sophisticated models as well as the most simple ones. Knowing your data at the start and following it all the way through will ensure that you do not fall prey to the dreaded “garbage in, garbage out” syndrome. 4. Remember the maxims of business economics. These maxims, included in Chapter 1 under “Maxims of Business Economics” on page 15 are more important than any software. For example, the admonition “Think first, calculate later,” applies whether you have an abacus or an elaborate simulation model. Having a powerful hammer requires you to be a careful carpenter!

3 MATLAB and Simulink Design Guidelines The Importance of Good Design It is easy to underestimate the importance of good design and good design guidelines for economic models. In this chapter, we first define “design,” and then provide guidelines for designing MATLAB and Simulink models. We also suggest simulation parameters that will work well for most models used in business economics. This chapter provides quite specific advice for those working in the MATLAB environment; for those working in other software environments, it suggests good practices that will need to be adapted to the specific environment. What is Design? The design of a model includes the applied analytical techniques used; the style used to organize the model; the methods of storing, naming, and reporting data; and the display of results of that analysis in tabular or graphical formats. We cover these topics as follows: 1. The fundamental architecture of models is covered in the application chapters. 2. The style guidelines, including methods of naming variables, ordering equations, laying out equations (or their graphical expressions such as in Simulink), and describing the model, are covered in this chapter. These guidelines are generally followed in the applications shown in the other chapters. 3. Methods of collecting and storing data, identifying the sources of the data (sometimes known as metadata), and reporting it are covered in this chapter and in Chapter 4, “Importing and Reporting Your Data.” 4. Methods of accurately displaying the most important data to maximize understanding and minimize distortion, misleading impressions, and distractions are covered in Chapter 17, under “Rules for Effective Graphics” on page 426. Why Use Good Design? There are several reasons for carefully considering how to design models, graphics, and tables: 1. Good design makes it easier for the creator of the model to understand his or her work, improve it, and use it. 2. Good design makes it much easier for others to understand a model, make suggestions, or ask intelligent questions about it.

Matlab and simulink design guidelines

27

3. Good design makes errors and weaknesses in logic more noticeable and therefore more likely to be corrected. 4. Good design makes the results more credible. 5. Good design makes the results more intelligible.

Setting Up the MATLAB Workspace The first place to start with good design is the design of the workspace. Just as it is difficult to find and complete work in a disorganized office, it is easy to work in a wellorganized software environment. We suggest the following ways of organizing the MATLAB software environment. 1. Create your own startup file, which should accomplish the following: a. Display any greetings or messages unique to the user. An example of this is in Chapter 1, under “A Simple Startup File” on page 7. b. Change the default directory to the one in which the model files are normally stored. c. Read in any parameters that are used repeatedly, such as simulation start and end dates for Simulink models. See “Simulation Parameters and the SIM command” on page 49. d. Input any optional settings. A suggested startup file is included in the Business Economics Toolbox that is a companion to this book. 2. Store your model files and any related data files in an entirely different directory, drive, or location other than the MATLAB pro gram files. You will probably install, delete, and reinstall various versions of the software many times, and keeping program files separate from data files is always good practice. 3. Back up your model and data files on a regular basis. 4. Within the location you have selected for your model and data files, make separate directories or other subdivisions for special toolboxes, projects, or data. For example, purchasers of this book that have downloaded the Business Economics Toolbox will want to place it in a separate directory within this location. 5. Document all the data files you create, even if it involves simply labeling the files properly so they can be distinguished by project or type. 6. Document all your custom-programmed files, including Simulink models and MATLAB script and function files (m-files). See “Documenting Your Models” on page 53. 7. Use consistent style guidelines in your models and m-files, even if they are not those recommended here! Note that different operating systems and different versions will require somewhat different syntax, commands, and installation procedures. However, following these simple suggestions will make your work more efficient.

Business economics and finance

28

Organizing MATLAB Models We will call a model in MATLAB a collection of commands that accomplish an analysis. Such a model can be quite simple and need not be dynamic, multiperiod, or multivariable. One of the powerful features of the MATLAB environment is the ability to open, review, edit, and save existing command files, as well as to create new ones. In this section, we briefly overview these files and suggest guidelines for creating, using, and describing them. MATLAB Scripts and Functions Most of the work done in the MATLAB environment is performed by command files that end in the suffix .m, such as print.m. These files may have been included as part of the MATLAB software, created by the user, or created by a third party. Because of the suffix, these files are often collectively called m-files. There are two types of m-files—scripts and functions. Scripts are commands that take no argument—they perform exactly the same tasks each time. Scripts operate on the data already in the workspace, which can be directly accessed. An analogy in the physical world are commands such as “go to sleep” or “blink your eyes.” These commands mean essentially the same thing to a person, no matter what the context. An example in the physical world is the command “run.” It only makes sense if you provide an additional parameter, namely a direction in which to run. Functions, on the other hand, are designed to operate on the arguments provided to them and can return specific output. In addition, functions operate within a separate workspace. Only the data you provide them (through the arguments native to the function) can be used in function calculations. Similarly, only the output specifically generated by the function will be available in the workspace afterwards. Functions can be very simple or very complex. For example, the command abs(7) calls the abs function to calculate the absolute value of the argument to the function 7. There is one argument and one output. Other commands take multiple arguments and return multiple outputs. Callbacks A command file that runs a set of commands when prompted by another command is sometimes called a “callback.” Callbacks that are customized to a specific model can be very useful. We discuss their use for Simulink models in “A Master Simulation Callback” on page 52. They are also used to execute tasks specified by a user’s interaction with a graphical user interface (GUI), although we do not cover this topic in this book. Design Guidelines for m-files This is not a book on programming. However, there are some style guidelines that we follow in creating MATLAB commands, including both scripts and functions: 1. Describe your m-file. MATLAB reserves a specific part of an m-file for this purpose. The H1 or Help line which follows the line that begins the file will be displayed in

Matlab and simulink design guidelines

29

certain listings of the files in a directory. Make sure you include a description here when you create an m-file. Describe the various sections of your m-file using comment lines. 2. Make commands and models as simple as possible. Do not overengineer your model or make it more complex than it already is. 3. Make commands robust. A robust method is one that works well under different circumstances. Try to make your applications robust enough to survive small human or computer errors—and to stop when major errors are committed. 4. Use hierarchy to organize. A well-designed model is often modularized—it is put together in different building blocks. Using such an approach makes it much easier to troubleshoot and to run consistently well. It is also a tremendous cost savings as further revisions are likely to be requested when just one or two sections of the command need to be updated. MATLAB has several attributes that make it easier to use a hierarchical, modular approach. In Simulink these include the ability to organize portions of a model into a subsystem, and in MATLAB the ability to use functions and subfunctions which operate in a separate workspace.23a 5. Whenever possible, separate data, parameters, and calculations. This makes your programs more flexible, powerful, and transparent. 6. Make sure that the input data, important intermediate results, and output data are provided to the user. This again makes the program more transparent and easier to use over time. As an aid to this, consider the recommendations for the use of data structures in Chapter 4 under “Using Structures to Organize Data” on page 74. 7. In models that perform multiple tasks, consider including commands that cause information on the progress of the tasks to be displayed in the workspace. “Master Simulation Callback” on page 58 is an example of an m-file in which different sections are described by comment lines and which causes information to be provided to the user at different stages. 8. Carefully consider how to name your m-files, so that they do not confuse the user, duplicate another command filename, or become either too specific or too general. Initializing a Model We recommend that a model be initialized by a separate program. Such a program will often call up the data, and request any additional parameters from the user. It may also run the required functions (after having supplied the data), and then save and report the results. Initializing a MATLAB Model Typically, models created within MATLAB are initialized manually when first developed. Over time, a well-developed model can be initialized in a script 23a

A “workspace” is a section of computer memory.

Business economics and finance

30

m-file. We sometimes call this a “Master [project name]” m-file since it will do all the necessary steps to open the model, input the data, run the simulation, and save and display the output. Initializing a Simulink Model We recommend that a Simulink model be initialized by a special callback program for this specific use. See “A Master Simulation Callback” on page 52. We also provide such a callback in the Business Economics Toolbox that is a companion to this book.

Introduction to Simulink Models One of the major advantages of working within the MATLAB software environment, especially with Simulink, is the ability to comprehensively model and then simulate complex, dynamic economic phenomena. By dynamic we mean changing over time. Most problems in business economics and finance involve multiple variables that change over time. Thus, simulation models are a natural and powerful tool for these problems. Simulink is not the only environment that allows simulation modeling, and indeed we present other applications of dynamic models in this book. However, Simulink has at least two significant advantages over most other environments: 1. Economic models are typically described as a system of equations involving many variables and some fixed parameters which change over time. These same equations can be modeled in Simulink but in a graphically intuitive way, like using building blocks. This is often easier than describing the same model using equations. 2. Simulink models can be constructed in a hierarchical fashion. A number of equations—all constructed and displayed graphically—can be organized into a separate subsystem within the overall model. These subsystems, in turn, can be organized to provide an understandable top-level view of the entire model. Constructing and visualizing a model in this manner makes it much easier to understand both the “big picture” and the specifics. In addition to these distinctions, Simulink models can use the vast library of MATLAB functions, as well as specialized libraries for specific purposes. The Simulink Model Schematic After a brief review, it is fairly easy to read a Simulink model. We say “fairly easy” because it is much easier to understand than the same systems described as a set of equations, but harder to describe than, say, calculating the sales tax on a hamburger.24 Because a Simulink model is illustrated in a way that shows how one variable affects another, we sometimes call the illustrations a schematic of a model. It is easiest to think of a Simulink model as an active flowchart with variables flowing from one end of the page to another.25 The variables used in the model are introduced on the left side of the page in boxes that contain their definitions. Other boxes perform all types of functions and operations. Lines connect these boxes indicating that the results of

Matlab and simulink design guidelines

31

their calculations are sent as signals down “wires” or “pipes” to the next block. By following the wires, you can see directly how one variable affects another and, ultimately, how all the inputs result in the output. Time and States in a Simulink Model Simulink models are actually a set of mathematical difference equations displayed as graphical entities in a set of systems and subsystems. Time is an essential element in a dynamic system. For each time period, variables are fed into the model, used in calculations, and then the results are reported. The results from one period are available for use in the next period. Because a change in a variable in one time period can cause further changes in the next, running the model involves simulating the effects of all the variables on each other over multiple time periods. While it is straightforward to think of Simulink models as a set of self-executing blocks in a flowchart, this is not technically correct. The equations calculate states of the model for each tick of the clock. Each block then provides information to the model at the next tick of the clock. Some blocks retain their states after each tick of the clock and can use that information at the next tick. Others, such as a simple multiplication block, do not.26 Many blocks use parameters that affect the operations they perform.

Example Simulink Models We start with a few examples which will illustrate how a Simulink model can perform complex, multistage calculations. Example Economics Model In Chapter 5, “Library Functions for Business Economics,” we illustrate a simple model that projects sales given a change in price. The model incorporates a number of specialized business economics blocks that are described in that chapter. The house net benefit model described next is more complex but does not use any specialized blocks, so we introduce it first. Some readers may want to look ahead to Chapter 5 to see the other model which is described in “Example Simulink Model” on page 114. House Net Benefits Model Figure 3-1, “Simulink model example: house net benefits,” illustrates a Simulink model that calculates the costs and benefits of owning a home. The model incorporates both the 24

Describing the income tax levied on the earnings needed to buy that hamburger, however, is probably a different story. 25 We rely on some of our style guidelines here. A user could design a Simulink model so that variables affect each other haphazardly with blocks all over the page. However, that would defeat at least one of the purposes of using this approach—an easier-to-understand presentation. 26 See Using Simulink, Version 5 Guide (published by The MathWorks), Chapter 2.

Business economics and finance

32

costs of ownership (including interest, insurance, and maintenance) as well as the benefits (the rental equivalent of living space, the tax deduction for mortgage interest payments, and any capital gain or loss on sale). This is the type of analysis that is frequently done—people commonly talk about “making money on a house”—but rarely done properly. To properly account for all these variables over a multiple-year time frame is a serious undertaking.

Top View In the top view of the model, the flow information starts in the upper left of the schematic in Figure 3-1 in the box labeled “home value subsystem.” In this subsystem, we calculate two variables: the initial value of the home and the current value. Both these variables are needed to calculate the total costs and benefits. We also see that, once calculated, the values for initial value and current value are used in other subsystems. Visually, it appears that the values of these variables go through the wires or pipes to the next subsystem. The visual appearance is consistent with reality because the values that emerge

FIGURE 3-1 Simulink model example: house net benefits. from the set of equations represented in one subsystem flow into equations represented by another subsystem. The results from the home value subsystem are used in two other sub-systems: (1) Net Benefits and (2) Costs and Rental Value. The results of the equations in these systems are also shown being summed (in the block showing the Greek letter sigma), being collected

Matlab and simulink design guidelines

33

into variables that will be saved in the workspace for later review, and being represented graphically in a “scope.” Costs and Rental Value Subsystem The equations within the Costs and Rental Value subsystem are illustrated in Figure 3-2, “Costs and rental value subsystem.” You will note that the pipes running into a subsystem are illustrated within that sub-system as inport (input) blocks, which should be labeled with the proper variable name. Those running out are called output or outport blocks. Other Costs Subsystems Subsystems can nest inside one another so that the user can build multiple levels of a model and work or illustrate one level at a time.

FIGURE 3-2 Costs and rental value subsystem The Cost Shares subsystem (which appears within the Cost and Rental Value subsystem) is illustrated in Figure 3-3, “Simulink model example: cost shares subsystem.” Within that subsystem is still another layer which is the subsystem illustrated in Figure 3-4, “Simulink model example: cost subsystem.” Output Blocks Returning to the top-level view in Figure 3-1, “Top-level view of Simulink model,” we see the results of multiple calculations are the variables net benefit and costs_benefits. These are deposited into the to_workspace variable blocks that list the variable names. Using these blocks you can inspect, analyze, and make further calculations with the resulting values.

Business economics and finance

34

Business Economics and Finance with MATLAB®, GIS, and Simulation Models Business Economics and Finance with MATLAB®, ...

Author: Patrick L. Anderson

7 downloads 20 Views 4MB Size

### Sections

Sec | Instructor | Lecture | TA | Recitation/Computer Lab |
---|---|---|---|---|

501 | Joung Dong Kim | MWF 10:20-11:10am HECC 207 | Sheagan John | T 9:10-10:00am Haynes Engineering Building 223 R 9:10-10:00am BLOC 126 |

502 | Joung Dong Kim | MWF 10:20-11:10am HECC 207 | Sheagan John | T 10:20-11:10am Haynes Engineering Building 223 R 10:20-11:10am BLOC 126 |

503 | Joung Dong Kim | MWF 10:20-11:10am HECC 207 | Sheagan John | T 11:30-12:20pm Haynes Engineering Building 223 R 11:30-12:20pm BLOC 126 |

504 | Joung Dong Kim | MWF 10:20-11:10am HECC 207 | Dustin McPhate | T 12:40-1:30pm Haynes Engineering Building 222 R 12:40-1:30pm BLOC 124 |

505 | Joung Dong Kim | MWF 10:20-11:10am HECC 207 | Dustin McPhate | T 1:50-2:40pm Haynes Engineering Building 222 R 1:50-2:40pm BLOC 124 |

506 | Joung Dong Kim | MWF 10:20-11:10am HECC 207 | Dustin McPhate | T 3:00-3:50pm Haynes Engineering Building 222 R 3:00-3:50pm BLOC 124 |

507 | Joung Dong Kim | MWF 11:30-12:20pm HECC 207 | Li Ying | T 9:10-10:00am Haynes Engineering Building 222 R 9:10-10:00am BLOC 124 |

508 | Joung Dong Kim | MWF 11:30-12:20pm HECC 207 | Li Ying | T 10:20-11:10am Haynes Engineering Building 222 R 10:20-11:10am BLOC 124 |

509 | Joung Dong Kim | MWF 11:30-12:20pm HECC 207 | Li Ying | T 11:30-12:20pm Haynes Engineering Building 222 R 11:30-12:20pm BLOC 124 |

510 | Joung Dong Kim | MWF 11:30-12:20pm HECC 207 | Adam Deaton | T 3:00-3:50pm Haynes Engineering Building 223 R 3:00-3:50pm BLOC 126 |

511 | Joung Dong Kim | MWF 11:30-12:20pm HECC 207 | Adam Deaton | T 4:10-5:00pm Haynes Engineering Building 223 R 4:10-5:00pm BLOC 126 |

512 | Joung Dong Kim | MWF 11:30-12:20pm HECC 207 | Adam Deaton | T 5:20-6:10pm Haynes Engineering Building 223 R 5:20-6:10pm BLOC 126 |

516 | Joseph Edward Kahlig | TR 9:35-10:50am HELD 105 | Ayo Adeniran | M 11:30-12:20pm Haynes Engineering Building 134 W 11:30-12:20pm BLOC 123 |

517 | Joseph Edward Kahlig | TR 9:35-10:50am HELD 105 | Ayo Adeniran | M 12:40-1:30pm Haynes Engineering Building 222 W 12:40-1:30pm BLOC 124 |

518 | Joseph Edward Kahlig | TR 9:35-10:50am HELD 105 | Ayo Adeniran | M 1:50-2:40pm Haynes Engineering Building 222 W 1:50-2:40pm BLOC 124 |

522 | Joseph Edward Kahlig | TR 11:10-12:25pm HELD 105 | Ryan Malthaner | M 11:30-12:20pm Haynes Engineering Building 223 W 11:30-12:20pm BLOC 126 |

523 | Joseph Edward Kahlig | TR 11:10-12:25pm HELD 105 | Ryan Malthaner | M 12:40-1:30pm Haynes Engineering Building 223 W 12:40-1:30pm BLOC 126 |

524 | Joseph Edward Kahlig | TR 11:10-12:25pm HELD 105 | Ryan Malthaner | M 1:50-2:40pm Haynes Engineering Building 134 W 1:50-2:40pm BLOC 123 |

525 | Gregory Stephen Klein | TR 2:20-3:35pm HECC 110 | Austin Conner | M 3:00-3:50pm Haynes Engineering Building 223 W 3:00-3:50pm BLOC 126 |

526 | Gregory Stephen Klein | TR 2:20-3:35pm HECC 110 | Austin Conner | M 4:10-5:00pm Haynes Engineering Building 223 W 4:10-5:00pm BLOC 126 |

527 | Gregory Stephen Klein | TR 2:20-3:35pm HECC 110 | Austin Conner | M 11:30-12:20pm Oceanography & Meteorology 206 W 11:30-12:20pm BLOC 124 |

M01 | Saikat Biswas | TBA | TBA |

## 0 Thoughts to “Tamu Math 151 Matlab Assignments Restaurant”