Docsity
Docsity

Prepare-se para as provas
Prepare-se para as provas

Estude fácil! Tem muito documento disponível na Docsity


Ganhe pontos para baixar
Ganhe pontos para baixar

Ganhe pontos ajudando outros esrudantes ou compre um plano Premium


Guias e Dicas
Guias e Dicas

Business Economics, Notas de estudo de Engenharia Elétrica

Business Economics

Tipologia: Notas de estudo

2016

Compartilhado em 21/10/2016

heitor-galvao-12
heitor-galvao-12 🇧🇷

4.6

(315)

387 documentos

Pré-visualização parcial do texto

Baixe Business Economics e outras Notas de estudo em PDF para Engenharia Elétrica, somente na Docsity! Business Economics and Finance with MATLABº, GIS, and Simulation Models Business Economics and Finance with MATLAB®, GIS, and Simulation Models 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. 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 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 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. 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 Business economics and finance 2 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 percent- sign [%] 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. How to use this book 5 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: Business economics and finance 6 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. How to use this book 7 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 Business economics and finance 10 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. How to use this book 11 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 Business economics and finance 12 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. How to use this book 15 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. 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 data and error process Strong, often unverified 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 Mathematical and simulation models in business economics 17 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 two- dimensional. 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. Business economics and finance 20 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! Mathematical and simulation models in business economics 21 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. Business economics and finance 22 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! Mathematical and simulation models in business economics 25 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. 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 well- organized 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. Matlab and simulink design guidelines 27 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 Business economics and finance 30 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. Matlab and simulink design guidelines 31 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 Business economics and finance 32 FIGURE 3-4 Simulink model example: cost subsystem. 3. Allowing the user to logically group the systems, subsystems, and building blocks of your model 4. Improving the speed of building and troubleshooting models Based on these objectives, we have developed a set of style guidelines that you can use or adapt to meet your needs. Major Style Guidelines: Simulink The major graphical styles we recommend and use for Simulink models are described in Table 3-1, “Major Style Elements for Simulink Models.” Style of Model Overview and Subsystems We discuss how to organize the structure of Simulink models in “Organizing Simulink Models” on page 45. In this section, we discuss style guidelines for the display of such models. Simulink models have an overview pane that covers the entire model and subsystems within the model that can be illustrated in separate panes. We suggest slightly different design guidelines for the top-level view and for the subsystems. Top-Level View The top-level view of every model should include the following: • A title properly stating the purpose of the model. • Major subsystems highlighted by drop-shadows and labeled. • Connections among the subsystems that are, where appropriate, made using multiplexed connector lines.27 Matlab and simulink design guidelines 35 • If used, a clearly labeled initiation block would show up in red on the computer screen of the user. • A description box at the bottom describing the purpose of the model. The author of the model, revision number, and date should be included. 27 In the example shown in Fig 3-1, we could have used multiplexed lines to connect the major subsystems. However, in order to show the different streams of data flowing from the first subsystem, We chose to reveal the number and titles of each by de-multiplexing the signals before bringing them into the subsystem on the right. The Simulink blocks that perform the combining of multiple lines and then separating them are called Mux and Demux. TABLE 3-1 Major Style Elements for Simulink Models Element Style Comments Major subsystem Large box, drop shadow This style highlights the most important portions of the model and makes use of one of the most important advantages of Simulink: the ability to easily grasp how data in a model flows from one group of calculations to another Description box Small box in bottom of top- level model view Should describe the title of the model, the author(s) and sponsoring organization, and the revision number or date. The Model Info Simulink block can be used for this purpose Initialization block A small block labeled “initiation block,” which runs an initiation script when selected and clicked; this is typically outlined in red Runs the initiation script that sets default values, reads in data, and provides parameters used in the simulation Titles Bold letters at the top of the frame that state the purpose of the model or subsystem Use a consistent font and type size, and place in the same position in each view Subsystems • Subsystems need not have initiation blocks or description boxes. • Subsystems can have more text when needed to explain the model. • Subsystems can include scopes, graphs, and other modules that are useful in debugging or checking results but which would clutter up the top-level view. Example: Top-Level View Figure 3-5 shows the top-level view of an economic impact model that is notable for its simplicity. Business economics and finance 36 FIGURE 3-5 Top-level view of Simulink model. Organizing Simulink Models Models should be structurally well organized, for a number of reasons, including: • A well-organized model reflects well-organized thinking. • As no system is perfect, good organization helps you catch errors and debug quicker. • Good organization helps convince your model’s users (or consumers of your model’s output) of the integrity of your approach. Given this motivation, we recommend the following guidelines for organizing your model: 1. Identify the major factors that drive the other variables and combine them into one or more sets of inputs. 2. Collect similar inputs into major subsystems that can be summarized by a single concept. Mask the subsystems so that the top level of the model shows a properly labeled subsystem containing related variables, rather than a tangle of signals and individual variables. 3. Collect similar output variables together in masked subsystems with inputs created for input and intermediate variables. 4. Place the input variables on the left side of the top-level model view and output variables on the right. This makes the model read the same way as sentences in English and other languages.28 5. Connect the subsystems together, to the extent possible, using signals that are multiplexed into big pipes. Where possible, avoid overlapping the signal pipes or crossing them. Matlab and simulink design guidelines 37 Code Fragment 3-2. Help Information in Masked Subsystem Double click to start simulation. Initialization: For the Initialization portion of the block you should add the following: 1. A description of the block in the field allotted for Mask Type. 2. Any commands needed for variables that must be available only within the space allotted for calculations made within the masked block. For initialization commands this is usually nothing. The MATLAB help system provides excellent guidance on this topic. Setting Parameters for Initialization Blocks: Highlight the block, then use gcb to find the name. Then use the following code line to set the name of the block: Code Fragment 3-3. Setting Parameters for Blocks set_param(gcb, 'name', 'initialization:') It will then show up properly on the model browser.29 See Figure 3-6, “Initialization block in a Simulink model.” Running Initialization Scripts on Command To make the block call an initialization script you have already written, take the following steps: 1. Right-click on the block and issue the Block Properties command. 2. In the panel marked “callbacks,” select Open Function and insert the name of the initialization script you wish to call. This will cause the script to run whenever you double click on the block. 3. While in this property editor for the block, add descriptive text in the “general” panel and select the attribute you want duplicated. 4. Block Annotation in the panel: 29 This can also be done using the “Block Properties” menu for the subsystem, as described below. Business economics and finance 40 FIGURE 3-6 Initialization block in a Simulink model. Code Fragment 3-4. Self-Describing Variable for Blocks %<description> This will cause the phrase written as the description of the block to show up in the model window. As an alternative, you can also specify a pre-load call back, using the model properties dialog box. Simulation Parameters and the SIM Command The simulation model may not run if any one of a number of parameters is not set correctly. The following section describes the parameters to set for each simulation model, and how they are set. Time and Solver Parameters in Simulink One of the more confusing aspects of Simulink can be its time and solver parameters. For many challenges in business economics, these can be set quite simply as discrete units of time that are consistent with the conventional description of the problem at hand. Variables that are measured only at specific intervals are known as discrete variables within the mathematically precise MATLAB environment. Most business variables such as sales, revenue, profits, employees, etc., are typically measured in discrete intervals. Simulink has the power to deal with problems in mathematics that require continuous variables and solvers that find solutions for more difficult (in a matrix algebra sense) problems. This power is often not required for business economics problems. However, a few applications demonstrated later in this book—such as iterative models in Chapter 10 and dynamicroprogramming in Chapter 11—will make use of it. Matlab and simulink design guidelines 41 TABLE 3-3 Key Simulation Parameters Parameter Suggested Settings Comments Start time Current year or period (e.g., quarter or month); may use Tstart variable Business problems often have time as the key index Stop time End of forecast period; may use Tstop variable Use same units as for start time Solver Fixed-step, discrete Most business problems take place in a time period that can be indexed using specific time intervals Fixed-step size Unit of time, such as year, month, or quarter; may use Tstep variable Must match the start and stop times Setting Parameters through a Menu Simulink allows key parameters to be set through a menu, and this is the easiest way to get a single model started. The key parameters are described in Table 3-3, “Key Simulation Parameters.” Simulink has a menu that allows the manual setting of these parameters. The menu can be reached by the Simulation|Parameters keystroke sequence or by manually selecting the menu item. This ad hoc method may be sufficient for many purposes, but there is a quicker method for those that routinely model business economics phenomena. We describe a method of automating the process of setting these parameters using the SIM command with the selection of specific options. The SIM Command The SIM command causes MATLAB to simulate a model using certain parameters defined by the command user or set by default. To review the options and general command syntax, you can review the Help information for the command.30 We recommend that users explicitly set the options described below and provide code fragments showing how to set them. Workspace and timespan: Workspace and timespan are important arguments. The workspace is the (virtual) subset of the universe in which variables exist. If the variables you create are in the base workspace, then you need to work in that workspace. Normally, that is what happens. However, computer operating systems usually set up multiple workspaces so that variables in one do not leak into another. For example, MATLAB sets up separate workspaces for functions. 30 This can be obtained by typing help sim at the command prompt or by looking through the Simulink user guide. Business economics and finance 42 The script file “Master Simulation Callback” is in the appendix to this chapter. Using the Master Simulation Callback The callback will run the example economics model illustrated in Chapter 5, “Library Functions for Business Economics,” starting with “Example Simulink Model” on page 114. Documenting Your Models Documenting your model is an important and often left-to-the-end step. The following steps help document your model. They can be accomplished while building or adjusting it. Masked Message Boxes Message boxes help you know what is going on in your model and communicate that to other users. An easy way to create a message box in Simulink is to create a masked subsystem. This is straightforward: 1. Create a subsystem in your model using the Simulink menu. 2. Edit the subsystem. 3. In the dialogue box created by the EditlMask command, select the Icon tab. 4. Type in the drawing box the disp or display command with the variable you want displayed as the argument. This method has limitations such as the inability of disp to take more than one argument. The following examples show how you can use the simple method when needed and find creative ways around the disp limitation. Trigger Boxes Many times you want to model behavior that starts when some other variable reaches a certain level or on a certain date. You can visually remind users of your model with trigger boxes. For example, if you have a trigger date in your model, you could define a variable called trigger that is equal to the trigger date. Then, using a masked subsystem, specify the icon for the subsystem. In the icon dialogue box for a masked subsystem type: disp(trigger) The trigger date then appears, magically, right in the box when you look at the model. Matlab and simulink design guidelines 45 Callback Messages We suggest that complex simulation models be initialized by a callback program which loads the variables and sets the simulation parameters. The same program can simulate the model, perhaps using two sets of variables. This approach will be more advantageous to the user and easier to debug if you include messages to the user in the callback program. This is quite easy as shown in the following example: Code Fragment 3-8. Messages in a Callback % load variables load myvariables disp('variables loaded...') whos; In the example, the callback loads the variables and after doing so displays a short message in the command window indicating this step was successfully accomplished. Then follows a whos command which will cause all the variables in the workspace to be individually listed as well. Complex String Arrays Sometimes a simple one-line character string is not sufficient for your message. In such cases, you create a character array that includes more than one string. This allows you to display multiple lines. You can also change character arrays to cell arrays, which allows for more precise addressing of the elements.32 The following code fragment illustrates this. Code Fragment 3-9. Character Arrays % create character array s = char('Hello', 'Neal!'); % create similar cell array scell = {'Hello', 'Neal') Business economics and finance 46 % convert character array to cell array schar = cellstr(s) % get information on string functions help strfun % display arrays disp(s) disp (scell) disp (schar) The code fragment above will create three different variables containing the same information. The following fragment shows the result of the display commands for the three variables. Code Fragment 3-10. Character and Cell Array Displays Hello Neal! 'Hello' 'Neal!' 'Hello' 'Neal!' Using Strings in Message Boxes: You can use these different methods of storing and displaying strings in Simulink message boxes. First, create a character array (for example, “s”) with the required text information. Then place the following command in an icon dialogue box or later in a callback or similar script file: disp(s); MATLAB will then create a two-line display such as that in the code fragment above. String Commands The use of strings to document models can be tricky because the character array data type is different from the data type of most numbers. Therefore, mixing strings with numbers requires careful handling including the use of special commands. While we will not provide a tutorial on the different data types in this book, we suggest a few quick references for practitioners. 1. Use the MATLAB help resources for string functions as shown in “Character Arrays” on page 55, as well as for strings in general. This can be accessed by simply typing help strings in the command window. 2. Use the num2str or int2str commands to convert numbers or integers to strings, especially when you want to include a number in a sentence. 32 We will discuss character arrays (strings) and related functions shortly. Matlab and simulink design guidelines 47 33 See also MathWorks solution 9009 for more details. These and other technical notes can be accessed through The MathWorks Web site. %------------------------------------------------- % Time Parameters (may be in .mat file) ; Tstart = 2003; Tstop = 2012; Tstep = 1; Years = [Tstart:Tstep:Tstop]'; %make column vector; % use in graphing % ------------------------------------------------- % Set model name modelname = 'economics_example'; %-------------------------------------------------- % II. Get Data %-------------------------------------------------- % Get data % Option 1: from GUI (workstation) or from HTML (Web % server), % Option 2: get data from .mat file % Load workspace (.mat) file, if necessary % (make sure file is located in reachable % directory.) % load sample.mat; % Option 3: Enter base data in callback: % Input Variables and Parameters, and echo in % workspace display('Echoing Key Variables and Parameters.'); echo on; % Input1 = 100; % Input2 = 100; % Input3 = 100; % ----Inputs to Initialize economics_example Elasticity = −1.0; InitialIncome = 1000000; growth = .01 + rand (size(Years))*.03; % 1% secular growth trend, plus random information AverageGrowth = mean(growth); % calculated mean growth % ----end inputs for economics_example display('Data read in.') echo off; %-------------------------------------------------- % III. Initial Variable Calculations (if needed) %-------------------------------------------------- %-------------------------------------------------- % IV. Simulation %-------------------------------------------------- % Simulate Model % Sim command takes model, timespan, options, and % external input arguments. % Options structure and Timespan should be set Business economics and finance 50 % above. % Simulation Parameters % These should be entered in the 'simulation % parameters' part of the Simulink model or through % the SIMSET command. % Source workspace should be set to 'current' for % Web server applications; % 'base' is default and works for workstation % applications. % % The following structure (named here "sset") can % be used to capture multiple parameters,including % model, timespan, options (including workspace), % and external inputs. sset = simset ('SrcWorkspace', 'current'); sim(modelname, [Tstartr:Tstep:Tstop], sset, []); display('Model Simulated.') % Show variables in workspace, if desired % Delete for Web server applications whos %-------------------------------------------------- % V. Graph Results %-------------------------------------------------- display('Graphing Results.'); % Define variables used for graphing millions = 1000000; billions = 1000 * millions; % Assemble variables for graphing purposes % (using example variables; substitute for different % model) Y1 = [Income./millions]; Y2 = [Sales./millions]; % Call specific graphing commands, or call graphing % callback here. figure(21), plot(Years, Y2), legend('Constant Growth', 'Varying Growth'); title('Income With Varying and Constant Growth Rates', ... 'fontweight', 'bold'); Xlabel('Years'); Ylabel('$ Millions'); figure(22), bar(Y2), legend('Sales') ; title('Economics Example: Sales Before and After Policy Change', ... 'fontweight', 'bold'); Xlabel('Years'); Ylabel('$ Millions'); % label years j = num2str(Years); jk = cellstr(j); set(gca, 'Xticklabel', jk) ; %-------------------------------------------------- % VI. Run Base and Alternate Simulations (if Matlab and simulink design guidelines 51 % needed) %-------------------------------------------------- % base_alt_callback %---------------------------end-------------------- Business economics and finance 52 customers. Sometimes the most interesting government-provided information does not appear on the Web site, is released late, has confusing definitions, or is buried under a mountain of disclaimers and press releases. 4. Remember that information in a news story may not be accurate. The use of information in a news story, even from a reputable news organization, means the reporter and editor thought the information was interesting and that it met their reliability standards. Often, neither the reporter nor the editor have the background, training, or time to adequately review the information. Furthermore, news organizations are profit-maximizing firms. Their revenue is based on drawing in readers and viewers. Be sure to check the original source of the data, or properly indicate in your analysis that you used data reported by a source but not verified by you. A Warning on Internet Data It has become commonplace to assert that nearly everything is available on the Internet.36 In fact, much of the most useful information is not on the Internet. By “useful,” we mean information that is reliable, well-formed, and necessary to the task at hand. The vast majority of information on the Internet fails one or more of these tests. While the Internet seems like a gold mine of information, it should really be described as a gold-plated mine shaft, leading to both gold and sludge. With this in mind, consider the following warnings about Internet data: 1. Information that appears on Internet sites is often mislabeled, improperly described, incomplete, or just plain wrong. 2. Unless there is a revision date on the Web page, do not assume that the information is current. 3. If data is republished on one Web site but not completely described there, always check to see the original publisher or creator of the data. Reputable data providers usually provide links to those sites. 4. Almost anybody can establish a Web site and post information on it. 5. There should not be two standards for reliability. Ask the same questions about data gathered on the Web as data gathered from any other medium. 35 As an example of how little confidence this inspires, note that political campaign ads attacking other candidates often “cite” the “source” of their information using this style. The viewer then has no ability to judge the actual source and little ability to even confirm there is a source. 36 For example, in the cult car-tuner film The Fast and the Furious, the leader of a gang of racers tells the upstart that he knows he had been in prison because almost everything is available on the Internet, including the upstart’s criminal record. It turns out that the upstart is actually an undercover cop. The moral of the story—at least one of them—is that one should not trust information that almost anyone can post. Importing and reporting your data 55 Getting Data into a Model In this section, we will discuss some tools for getting data into your model, including: • A standard Web browser, along with MATLAB, Excel, or other analysis programs • Excel Link (which requires Microsoft Excel, a spreadsheet program) Getting Data into a Model In this section, we will discuss some tools for getting data into your model, including: • A standard Web browser, along with MATLAB, Excel, or other analysis programs • Excel Link (which requires Microsoft Excel, a spreadsheet program) Getting Data into a Model In this section, we will discuss some tools for getting data into your model, including: • A standard Web browser, along with MATLAB, Excel, or other analysis programs • Excel Link (which requires Microsoft Excel, a spreadsheet program) Getting Data into a Model In this section, we will discuss some tools for getting data into your model, including: • A standard Web browser, along with MATLAB, Excel, or other analysis programs • Excel Link (which requires Microsoft Excel, a spreadsheet program) Getting Data into a Model In this section, we will discuss some tools for getting data into your model, including: • A standard Web browser, along with MATLAB, Excel, or other analysis programs • Excel Link (which requires Microsoft Excel, a spreadsheet program) Getting Data into a Model In this section, we will discuss some tools for getting data into your model, including: • A standard Web browser, along with MATLAB, Excel, or other analysis programs • Excel Link (which requires Microsoft Excel, a spreadsheet program) Business economics and finance 56 Getting Data into a Model In this section, we will discuss some tools for getting data into your model, including: • A standard Web browser, along with MATLAB, Excel, or other analysis programs • Excel Link (which requires Microsoft Excel, a spreadsheet program) Getting Data into a Model In this section, we will discuss some tools for getting data into your model, including: • A standard Web browser, along with MATLAB, Excel, or other analysis programs • Excel Link (which requires Microsoft Excel, a spreadsheet program) Getting Data into a Model In this section, we will discuss some tools for getting data into your model, including: • A standard Web browser, along with MATLAB, Excel, or other analysis programs • Excel Link (which requires Microsoft Excel, a spreadsheet program) Getting Data from the Internet The growth of the Internet has been a boon to users of data. However, there are still many limitations in the availability, format, and reliability of data posted on the Web. To help you get your data in usable format, we offer a few useful tips and tools in the following pages, all based on a standard Web browser and Internet connection. Limitations of HTML We describe in Appendix I to this chapter the interesting history of the language that made the World Wide Web possible.37 This language, Hypertext Markup Language (HTML) allowed for innumerable hypertext links to establish a web of connections among pages of information. However, this great strength in linking was not matched in other characteristics, notably the maintenance of structure among data. The limitations of HTML described above have become more evident as Web usage has grown. This has motivated the development of the Extensible Markup Language (XML). XML is intended to maintain the structure of data. Information in XML is “marked up” to allow the recipient to understand the types of information that is being 37 See “Appendix I: XML and Structured Data” on page 83. 38 If you have yet to find the Web page at which to stare, see “Using Excel Link” on page 70. Importing and reporting your data 57 Code Fragment 4-1. URLREAD for Direct Internet Data Access % example of "urlread" command; checks web site, % downloads content, % searches for instances of specific words. 41 See Patrick L.Anderson, “Statistical Analysis of the Florida Presidential Election Results” and related Web pages on Michigan Results; available at: http://www.andersoneconomicgroup.com/Projects/policy/elections/statanalfl.htm; “Michigan Undervote Could Out-weigh Florida’s,” The Detroit News, December 13, 2000. 42 The Edmunds site is at: http://www.edmunds.com./ Also, see Chapter 12, “Applications of Finance,” especially “Depreciation” on page 301. 43 As noted above, Web queries are not reliable when used with Web pages generated by database programs. This is not the fault of the sponsor of the site, who is often attempting to provide data to a large number of users, most of whom are (unfortunately) not economists. % Note: must have active internet connection. s = urlread('http://www.andersoneconomicgroup.com/') s1 = findstr(s, 'Michigan Unemployment') s2 = findstr(s, 'Unemployment') % --end Using Excel Link One of the most useful features of MATLAB is its interface with Microsoft Excel, using the Excel Link Toolbox.44 Excel is a powerful, inexpensive, and nearly ubiquitous software for assembling and reporting data. Certain government data sources are pro vided in Excel format, and many businesses use it. Furthermore, Excel itself contains powerful file transformation routines that can be used to import data from other formats.45 Thus, some familiarity with the 44 Excel is a trademarked product of Microsoft Corporation. 45 Numerous observers have criticized Microsoft for embedding features in its software that make it more difficult to use with non-Microsoft software; I have also weighed in on this controversy. See, for example, Patrick L.Anderson, “Microsoft is Indeed Cyber-Bully,” The Detroit News, November 11, 1999. Indeed, the U.S. government’s antitrust lawsuits against Microsoft resulted in a judicial ruling that the Windows operating system had been designed to make it difficult to use non- Microsoft Web browsers. Excel Link Toolbox can make the real-life chore of getting the right data easier. Business economics and finance 60 The following discussion describes how this feature can be used in regular workstation sessions. Throughout we assume that the user is using a Microsoft Windows environment and an Excel 97 or later version.46 Even for applications that may later be ported to a Web server, this is a useful strategy for development and testing. Please refer first to the MATLAB product instructions for Excel Link if you are unfamiliar with it. Importing Your Data: A General Strategy We often employ the following general strategy for importing data: 1. Collect the initial numeric data in an Excel worksheet. The worksheet should list the title of the variable, note its source, note any limitations or cautions on its use, and include the number for the datum. This can be done in a simple table format. 2. Embed in the table the necessary Excel Link commands to put the variables into the MATLAB workspace. The first active column contains the name of the variable and the next columns contain the values in the data vector. The third column contains a definition statement in the form of variable_name = [amount1 amount2]. This can be entered manually or by using the concatenate command in Excel.47 3. Manually execute these cells to ensure that they properly send the correct data. See “Sample Excel Sheet for Inputting Data” below. Note that the MLEvalString command in the last column must refer to the cell that contains the definition statement. 4. Once the worksheet is completed and all the data entered, save and reopen the worksheet. This automatically transfers all the data into the MATLAB workspace. 5. Save the data in the MATLAB workspace to a .mat file. 6. Use the .mat file for MATLAB sessions. 7. When data needs to be updated or revised, one normally needs only to replace the numeric values, save and reopen the worksheet, and then resave the variables in the MATLAB workspace. Computer users today have multiple options, including running their workstations and servers on competing operating systems such as Linux or Unix. My inclusion of a discussion on Excel Link in this book does not constitute an endorsement of Microsoft’s operating systems. It does constitute an endorsement of using Microsoft Excel as a useful front end for obtaining many data sources, inputting it easily into MATLAB, and reporting or communicating it to others, including those who (by choice or by c ircumstances) use Microsoft products. 46 We have successfully used this feature with Excel 2000 and 2003. Please see the discussion on running Excel Link under different versions of MATLAB in “Appendix B: Excel Link Debugging,” on page 455 47 For example, the following statement will grab the variable title and the values and then form the proper definition statement: “=CONCATENATE(A2, "=[", B2, " ", C2, "];").” After one such statement is created properly, you can use the Edit|Fill command to create others in the same column, creating variable definitions for more rows of data Importing and reporting your data 61 Table 4-1, “Sample Excel Sheet for Inputting Data,” illustrates this strategy. Reporting Your Data A complementary use of Excel is to report data produced in your MATLAB sessions. This normally is done by using the getmatrix buttons in the Excel TABLE 4-1 Sample Excel Sheet for Inputting Data Variable Name Amount1 Amount2 Definition Statement Evaluation Statement Revenue 100 200 Revenue=[100 200] MLEvalString(D2) . toolbar. However, for repeated use of similar data, this process can be automated in the same fashion as importing data. The method for reporting your data is the same as for inputting the data with the following changes: 1. Define the range of cells into which you want to place the data calculated in MATLAB. Put the ap propriate headings and related formatting items in place as well. The data cells will be blank. 2. Put a getmatrix command in a nearby cell of the Excel spreadsheet which includes the name of the variable in MATLAB and the range of cells allotted for the variables. 3. Execute the command when the data are available. 4. Check to ensure that the correct data are in the correct cells. It is very easy to misspecify a cell range and end up with data in the wrong place. Debugging Excel Link See “Appendix B: Excel Link Debugging,” on page 455, which lists a number of tactics for debugging this useful but tricky utility. Reporting Your Results We discussed above the methods for getting data into your model. In this section, we discuss a few methods for getting data out of your model, including: • The diary command in MATLAB • The MATLAB Report Generator • Careful reporting in a function or script Business economics and finance 62 • You have many variables. • You have the same variables for each of several entities. • You want to collect descriptive information which may include text and numbers into one variable. • You want to pass groups of data back and forth to functions, or wish to organize or store information for several entities. • You find it easier to manage large amounts of data by first conceptually organizing information and then storing it according to group. Most business economists and others dealing with the issues discussed in this book will find themselves in these situations. Cell Arrays Cell arrays are variables in which objects of many types are put into “cells.” Cell arrays are like a warehouse with many rooms, each of which could be located by listing the room and the bin number. In MATLAB, cell arrays are distinguished by, among other things, their use of curly brackets. For example, in the following code fragment we create a cell array of variables and then extract them. Code Fragment 4-3. Cell Arrays % example of cell array usage % create cell array (empty) info = cell(2 , 2) % put in strings (note curly brackets) info{1} = 'first bit of information' % put in vector info{2} = [1 2 3 4 5] % put in matrix info{3} = [20 30; 40 50] info{4} = 'last bit of information' % now, get information out; address with curly % brackets info{4} % now, get information with plain addressing (note % format) info(4) Structures Structure data variables are another format in which you structure a variable so that it holds, with a rigorous logical structure, a number of “fields” that can each have a variable of a different type. Importing and reporting your data 65 Structures are similar to databases in that the entries are denoted as fields within an overall structure name. Fields can be added, deleted, or addressed using standard MATLAB commands. Structure Syntax Structures, like databases, are addressed using the database name and then a field name. The syntax, used by MATLAB delimiter so that any known variable within a structure can be addressed in MATLAB using the name of the structure and the name of the field. A similar convention is followed in other environments such as XML.48 In the following code fragment, the structure variable book is created and fields for the title, subtitle, author, and publisher (all strings) are inserted into the structure, followed by the numeric array (in this case a scalar) of the number of chapters. Code Fragment 4-4. Structure Syntax book.title = 'Business Economics and Finance' book.subtitle = 'Using Matlab, GIS, and Simulation Models' book.author = 'Patrick L. Anderson' book.publisher = 'CRC Press' book.number_of_chapters = [17] book book = book.title = 'Business Economics and Finance' book.subtitle = 'Using Matlab, GIS, and Simulation Models' book.author = 'Patrick L. Anderson' book.publisher = 'CRC Press' book.number_of_chapters = 17 publisher: 'CRC Press' 48 We describe later in this chapter rules for structured documents called the Document Object Model or the DOM. These rules are the basis for the XML data standard. In anticipation of that material, note how the variable.field syntax allows for different elements of a whole topic, which are related by the topic but are not of the same data type, to be grouped together in a logical fashion. MATLAB structures do not strictly follow DOM rules, but they do follow a larger convention that becomes quite helpful when the number of variables becomes large. Business economics and finance 66 Methods of Packing and Unpacking Structures MATLAB includes commands that create structures, “pack” information into them, and then “unpack” the information. Packing variables into a structure means creating the field for the variable and then putting the variable into that field. Think of packing as analogous to carefully packing a suitcase so that the shoes, socks, and all other items go into the right compartment. These commands include: • You can directly create a structure or, add a field to an existing structure by naming it and assigning information to it. • struct is a command that builds a data structure from variables in a workspace and names the fields in the structure. • cell is a command that builds cell arrays. • cell2struct and struct2cell are commands that take the elements of a structure or cell array and create a new variable in a different format. • rmfield, setfield, and getfield are commands that remove, set, and get a certain field within a structure. For example, you can create a structure and pack it with variables as follows: Code Fragment 4-5. Creating, Packing, and Unpacking a Structure % put in strings (note curly brackets) infostruct.intro = 'first bit of information' % put in vector infostruct.datal = [1 2 3 4 5] % put in matrix infostruct.data2 = [20 30; 40 50] infostruct.extro = 'last bit of information' % now, get information out; address directly infostruct.data2 % now, get information on entire structure infostruct %-------------------------------------------------- % Packing all at once %-------------------------------------------------- infostruct2 = struct ('first_info', info{1}, 'datal', infostruct.datal); infostruct Importing and reporting your data 67 Data Organizing Tools Organizing your data becomes increasingly important as the complexity of the project increases and as the number of projects multiply. The ability to organize data varies tremendously across different software environments. There are certain attributes we desire in a software environment that organizes data, such as: • A hierarchical structure which natively organizes details about a concept into a larger whole • The ability to directly address a specific field or entry in a table without wading through all entries • The incorporation and maintenance of metadata, or data about data, which allows for the documenting of data sources, inclusion of notes, and other essential information Discussion: Spreadsheets and Databases Spreadsheets are quite deficient in these attributes. They are inherently flat tables with no structure and with no direct connection between metadata and the data. While you can trick a spreadsheet into acting like a database, it is inherently a flat table. Relational databases are a large improvement over spreadsheets. They have structure, and a skilled user can document and enforce data integrity among related elements. However, the skill required is fairly high for such use; there is a reason why DBA (database administrator) is a common acronym while SA (spreadsheet administrator) is not.50 MATLAB has specific commands that allow it to directly query many relational databases. A Database Toolbox is available that allows MATLAB to query databases, import data, export data, and perform other tasks with relational databases. We do not describe this toolbox in this textbook, but you may wish to consider this toolbox if you regularly access large databases. Even if you do not wish to directly interact with a relational database, you can normally use data stored within it by exporting the data in one or more forms. Most databases can export information in flat files that can be read by MATLAB, and most can now export it in the XML format.51 50 Just to check, the author asked a search engine to find Web pages containing “DBA” and “database”; over 236,000 were found, many of which specifically referenced a database administrator. By contrast, 51,000 instances of “spreadsheet” were found also containing “SA.” Most of these turned out to be foreign words, other acronyms, or the surprisingly common use of novel contractions like that in the phrase “what’s a spreadsheet?” 51 For a discussion of XML, see “History of HTML, Other Formats, and XML” on page 84. Business economics and finance 70 A Note on GIS Databases In addition, the Mapping Toolbox includes commands for accessing data from Geographic Information Systems (GIS) databases, including the TIGER files maintained by the U.S. Census Bureau. We do not describe this toolbox in this textbook, but the use of GIS in analyzing retail sales and other elements of the economics of location and geography has been described in Chapter 13, “Modeling Location and Retail Sales,” on page 327, and Chapter 9, “Regional Economics,” on page 189. Creating Custom Structures Within MATLAB, we often wish to use the benefits of a relational database, specifically the ability to structure and organize data. These benefits can often be obtained by designing an application from the beginning to use data stored in MATLAB structures. In the preceding section, we described the general tools used in creating, packing, and unpacking structures. Additional Methods The methods described above do not exhaust the possibilities for exchanging data and reporting on the results of an analysis. Below we briefly mention three sets of methods; the first set will be available to most users with minimal or no additional cost. The second set will require substantial customization and additional programming. The third set is described in Chapter 16, “Bringing Analytic Power to the Internet.” Command History, Diary, and Notebook 1. For all users, the diary command allows for the commands to be collected in a file along with most of the command-line output. This allows for the results of a session to be replicated later on. 2. For all users, the command history window collects the commands you have typed in a session from which you can quickly create a script file. (The command history window appears at the user’s option in MATLAB 6 and later versions; type desktop and then use the View menu to open it.) 3. For those using Microsoft Word, the notebook command will collect input and output in a Word file. Even if you do not use Word, the file format may be accessible by your word processing software. Custom Interfaces You may wish to consider the following custom interf aces which will require additional software, are platform-specific, and may also require the assistance of a specially trained programmer: Importing and reporting your data 71 1. Using MATLAB as an engine to perform calculations demanded by a C or Fortran program, which is available on multiple platforms. 2. Creating MEX files from MATLAB m-files, which then can be run on other machines. 3. For those using Microsoft Windows computers, a custom Active-X interface can be created based on a client/server model. MATLAB has built-in functions that enable this approach. 4. For those using Microsoft Windows, a custom DDE (dynamic data exchange) interface can also be created which implements a peer-to-peer communication. Good descriptions of these possibilities are provided in other books on MATLAB.52 See also the MATLAB user guides. MATLAB Web Server In Chapter 16, “Bringing Analytic Power to the Internet,” we describe running applications on Web servers which can extend the potential reach of MATLAB analytics to anyone with a Web browser and an Internet connection. Appendix I: XML and Structured Data Limitations of HTML One of the problems of the World Wide Web is the limitation built into the basic HTML language used to display text, numbers, and graphics. HTML means Hypertext Markup Language, which means that the main purposes of HTML documents are to provide hypertext links to other sources of information (the ubiquitous links feature of Web pages) and markup capabilities. Adding links was a huge innovation, and it made the Internet more than an interesting device for dedicated academics and technophiles. However, the markup side of HTML was never designed to do much more than simply display information. Therefore, HTML pages that contain tables 52 See, in particular, D.Hanselman and B.Littlefield, Mastering MATLAB 6 (Upper Saddle River, NJ: Prentice Hall, 2001), Chapters 34 and 36. of data can display the data for a reader but normally cannot provide the hierarchy, source information, or easy communication with other programs. History of HTML, Other Formats, and XML A brief history of HTML and the emergence of newer standards will motivate the discussions that follow. HTML emerged from an older and much more sophisticated standard—Standardized General Markup Language or SGML. SGML was created in the 1960s, and the SGML standard was codified by ANSI in 1986.53 It is a truly international standard, and the ISO organization also maintains an SGML specification.54 Business economics and finance 72 <icon>$toolbox/MATLAB/icons/MATLABicon.gif</icon> <list> <listitem> <label>Testplots</label> <callback>testplot</callback> <icon>D://models/economics/economics_toolbox.jpg</ icon> </listitem> <listitem> <label>Help--not currently implemented</label> <callback>doc econ_toolbox_help/</callback> <icon>$toolbox/MATLAB/icons/book_mat.gif</icon> </listitem> <listitem> <label>Book Publisher (CRC Press) Web Site</label> <callback>web http://www.crcpress.com -browser;</ callback> <icon>$toolbox/MATLAB/icons/webicon.gif</icon> </listitem> <listitem> <label>Book Author (Anderson Economic Group) Web Site</label> <callback>web http://www.andersoneconomicgroup.com browser;</callback> <icon>$toolbox/MATLAB/icons/webicon.gif</icon> </listitem> </list> </productinfo> <!--See MATLAB Help for file input-output, regarding XML files, for discussion of info.xml file. --> <!--Prepared by Anderson Economic Group LLC for purchasers of Business Economics Using MATLAB, published by CRC Press. Use by license only. -- > <!--Note that MATLAB appears sensitive to indents and spacing in these xml files. Use "smart indent". --> Appendix II: Custom Data Structure Creation We provide below a custom script file for use in business valuations in which the same data will be collected for multiple businesses and then used for calculations. The data structure below is highly customized for this purpose; indeed, it is customized for valuation of a specific type of business, namely beer distribution. We discuss in Chapter 11, “Business Valuation and Damages Estimation,” the importance of using methods appropriate to both the industry and the business. Therefore, we provide no “one size fits all” routines. While this routine will not collect the data necessary to estimate the value of, say, a retailer or manufacturing firm, the structure of the program can be used for most projects in which a set of disparate data are collected for each of several subjects. You will note the following sections in the program: Importing and reporting your data 75 1. Naming the data structure 2. Checking key variables for both existence and reasonableness 3. Checking the overall number of inputs 4. Packing the variables into a data structure, which includes the metadata necessary for a user to later identify the source and intended application of the data Variables in This Custom Structure The purpose of describing this method in this chapter is to explain the method of creating a data structure, not to discuss the data. However, for those readers unfamiliar with the variables (or those who are waiting to read the chapters on business and valuation), we describe briefly the purposes of the variables in the script. • The name of the case is requested for each business for obvious reasons. • Data on sales history, costs, and profits are requested for each business. • Cost-of-capital data are also requested; the wacc variables are various estimates of the weighted average cost of capital for a firm. The data and its uses are discussed in Chapter 11, under “Example: Beverage Distributors” on page 272. Code Fragment 4-8. Creating a Valuation Data Structure % DATA_BD % Creates valuation data structure from workspace % variables. % Resulting data structure can be used in VAL_BD % (for beer distributors) % or can be modified for use in other valuation % tasks. % Note that data must already be in workspace for % command to work. % % uses MM toolbox (mmv2struct); can use STRUCT % instead. % See also VAL_ BD % % PLA June 9, 2003 % (c) 2003 Anderson Economic Group, % part of Business Economics Toolbox % Use by license only. %------------------------------------------------- % I. Get intended filename and any notes %------------------------------------------------- filenamestring = input('Enter name of file:', 's'); Business economics and finance 76 -------------------------------------------------- % II. Check individual data variables for % existence and reasonableness %------------------------------------------------- disp('Checking for necessary data in workspace ...'); % Insert placeholders, or warn user, for certain % variables if exist('name_of_case') % use entered data else warning('Missing name_of_case variable.'); end % price to retailer, if necessary to calculate if exist('ptr’) % use entered data messtemp = ['Using entered PTR ', num2str(ptr), '. '] ; disp (messtemp); clear messtemp; else ptr = sales_rev_base/sales_case_base; disp('Using calculated PTR.'); end % check amount if ptr > 30 warning('Calculated price to retailer exceeds $30. Recheck input data.'); elseif ptr < 10 warning('Calculated price to retailer less than $5. Recheck input data.'); end % salable assets------------------------------------ if exist('SalableAssets') %use entered data else SalableAssets = 25000; warning('No Salable Assets Entered. Using placeholder value of $25,000.'); end % discount rate on liquidation if exist('discount_rate_liq_sales') %use entered data else discount_rate_liq__sales = .25; warning('No discount rate on liquidation of assets entered. Using placeholder value of 25%.'); end % growth rates and wacc--------------------------- if growth mid >1 warning('Growth rates should be entered as decimals, such as ".05" rather than "5%".'); Importing and reporting your data 77
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved