OOP PROGRAMMING .tr



IE141-CE 209Introduction to Programming(Using Octave?)Asst.Prof. Dr. Mehmet MERKEP?? 2019–2020 FallTextbooks [Nagar 2018] Introduction to Octave for Engineers and Scientists.[Farrell 2015] Programming Logic and Design - Comprehensive Version 8e.Content1Computer Systems2Understanding Simple Program Logic3Octave GUI4Control Structures5Arrays6Plotting7Functions8Text Files 9Sound Files10Image Files COMPUTER SYSTEMSA computer system is a combination of multiple pieces of hardware and software required to process and store data using a computer.Hardware is the equipment, or the physical devices, associated with a computer. For example, keyboards, mice, speakers, and printers are all hardware.Software is a set of programs.Programs are instruction sets written by programmers that tell the hardware what to do. When you write software instructions, you are programming. This course focuses on the programming process.Software can be classified into two broad types: Application software comprises all the programs you apply to a task, such as wordprocessing programs, spreadsheets, payroll and inventory programs, and games. When you hear people say they have “downloaded an app onto a mobile device,” they are simply using an abbreviation of application. System software comprises the programs that you use to manage your computer, including operating systems such as Windows, Linux, or UNIX for larger computers and Google Android and Apple iOS for smartphones..Together, computer hardware and software accomplish three major operations in most programs: Input: Data items enter the computer system and are placed in memory, where they can be processed. Hardware devices that perform input operations include keyboards and mice. Data items include all the text, numbers, and other raw material that are entered into and processed by a computer, such as, facts and figures about entities, images, sounds, and a user’s mouse or finger-swiping movements. Processing: Processing data items may involve organizing or sorting them, checking them for accuracy, or performing calculations with them. The hardware component that performs these types of tasks is the central processing unit, or CPU. Some devices, such as tablets and smartphones, usually contain multiple processors. Writing programs that efficiently use several CPUs requires special techniques. Output: After data items have been processed, the resulting information usually is sent to a printer, monitor, or some other output device so people can view, interpret, and use the results. Programming professionals often use the term data for input items, but use the term information for data that has been processed and output. Sometimes you place output on storage devices, such as your hard drive, flash media, or a cloud-based device. (The cloud refers to devices at remote locations accessed through the Internet.) When you send output to a storage device, sometimes it is used later as input for another program. You write computer instructions in a computer programming language such as Visual Basic, C#, C++, or Java.The instructions you write using a programming language are called program code; when you write instructions, you are coding the program.Every programming language has rules governing its word usage and punctuation. These rules are called the language’s syntax. Mistakes in a language’s usage are syntax errors. Unless the syntax is perfect, the computer cannot interpret the programming language instruction at all.When you write a program, you usually type its instructions using a keyboard.When you type program instructions, they are stored in computer memory, which is a computer’s temporary, internal storage. Random access memory, or RAM, is a form of internal, volatile memory. Programs that are currently running and data items that are currently being used are stored in RAM for quick access. Internal storage is volatile—its contents are lost when the computer is turned off or loses power. Usually, you want to be able to retrieve and perhaps modify the stored instructions later, so you also store them on a permanent storage device, such as a disk. Permanent storage devices are nonvolatile—that is, their contents are persistent and are retained even when power is lost. After a computer program is typed using programming language statements and stored in memory, it must be translated to machine language. Machine language is also called binary language, and is represented as a series of 0s and 1s.Your programming language statements are called source code, and the translated machine language statements are object code. Each programming language uses a piece of software, called a compiler or an interpreter, to translate your source code into machine language. Although there are differences in how compilers and interpreters work, their basic function is the same—to translate your programming statements into code the computer can use. When you use a compiler, an entire program is translated before it can execute; when you use an interpreter, each instruction is translated just prior to execution. Usually, you do not choose which type of translation to use—it depends on the programming language. After a program’s source code is successfully translated to machine language, the computer can carry out the program instructions. When instructions are carried out, a program runs, or executes. In a typical program, some input will be accepted, some processing will occur, and results will be output. Besides the popular, comprehensive programming languages such as Java and C++, many programmers use scripting languages (also called scripting programming languages or script languages) such as Python, Lua, Perl, and PHP. Scripts written in these languages usually can be typed directly from a keyboard and are stored as text rather than as binary executable files.Scripting language programs are interpreted line by line each time the program executes, instead of being stored in a compiled (binary) form. Still, with all programming languages, each instruction must be translated to machine language before it can execute.Paradigms of ProgrammingA programming paradigm is a fundamental style of programming based on distinct concepts that shape the way programmers design, organize and write programs.Each paradigm is not just a programming style but usually involves an end-to-end approach for building systems, including analysis, design, implementation, testing, deployment and maintenance.Procedural (Structured, Imperative) ProgrammingControl structures govern the order of execution of computational steps called commands.Similar to descriptions of everyday routines, such as food recipes.Typical commands offered by imperative languages are assignment, I/O, procedure calls.Abstracts one or more actions into a procedure, which can be called as a single command (Procedural Programming).Object-Oriented ProgrammingBased on models of human interaction with real world phenomena.Data as well as operations are encapsulated in rmation hiding is used to protect internal properties of an object.Objects interact by means of message passing which applies an operation on an object.Objects are created by using templates called classes. This allows the programming of the classes, as opposed to programming of the individual objects.Classes are organized in inheritance hierarchies which provides for class extension or specialization.Declarative ProgrammingExpresses the logic of a computation without describing its control flow (tells what to do, not how to do it).Common declarative languages include those of database query languages (e.g., SQL, XQuery), regular expressions, logic programming, functional programming, and configuration management systems. Functional ProgrammingBased on mathematical theory of functions.The values produced are non-mutable.Impossible to change any constituent of a composite value.However, it is possible to make a revised copy of composite value.All computations are done by applying (calling) functions.Functions are first class values.All computations are done by applying (calling) functions.Functions are first class values.Logic ProgrammingAnswers a question via search for a solution.Based on axioms, inference rules, and queries (i.e., automatic proofs within artificial intelligence).Program execution becomes a systematic search in a set of facts, making use of a set of inference rules.Many other programming paradigms exist (constraint programming, symbolic programming, generic programming, + about 30 more at the time of writing).For this course, we use a scientific procedural language.Scientific procedural languages: To simplify small proof-of-principle computations, specialized scientific languages such as MATLAB?, and Octave? and symbolic manipulation languages such as MAPLE? or Mathematica? provide an easily learned high-level user interface to a unified built-in array of easily called and highly optimized numerical, scientific and graphical libraries. MATLAB code can be transformed into C++ through an add-on product while C++ and FORTRAN routines can be called by a MATLAB program with some effort. MATLAB is unavailable at many sites because of its substantial cost, although this can, however, increasingly be circumvented, through free software packages that imitate MATLAB commands. This course accordingly employs the most widely employed alternative, GNU Octave. UNDERSTANDING SIMPLE PROGRAM LOGICA programmer’s job involves writing instructions (such as those in the doubling program in the preceding section), but a professional programmer usually does not just sit down at a computer keyboard and start typing. The program development cycle can be broken down into at least seven steps: Understand the problem. Plan the logic. Code the program. Use a compiler or interpreter to translate the program into machine language.Test the program.Put the program into production.Maintain the program. Understanding the Problem: Professional computer programmers write programs to satisfy the needs of others, called users or end users. Examples of end users include a Human Resources department that needs a printed list of all employees, a Billing department that wants a list of clients who are 30 or more days overdue on their payments, and an Order department that needs a Web site to provide buyers with an online shopping cart. Because programmers are providing a service to these users, programmers must first understand what the users want. When a program runs, you usually think of the logic as a cycle of input-processing-output operations, but when you plan a program, you think of the output first. After you understand what the desired result is, you can plan the input and processing steps to achieve it. Suppose the director of Human Resources says to a programmer, “Our department needs a list of all employees who have been here over five years, because we want to invite them to a special thank-you dinner.”On the surface, this seems like a simple request. An experienced programmer, however, will know that the request is incomplete. For example, you might not know the answers to the following questions about which employees to include: Does the director want a list of full-time employees only, or a list of full- and part-time employees together? Does she want to include people who have worked for the company on a month-tomonth contractual basis over the past five years, or only regular, permanent employees? Do the listed employees need to have worked for the organization for five years as of today, as of the date of the dinner, or as of some other cutoff date? What about an employee who worked three years, took a two-year leave of absence, and has been back for three years? The programmer cannot make any of these decisions; the user (in this case, the Human Resources director) must address these questions. More decisions still might be required. For example: What data should be included for each listed employee? Should the list contain both first and last names? Social Security numbers? Phone numbers? Addresses? Should the list be in alphabetical order? Employee ID number order? Length-of-service order? Some other order? Should the employees be grouped by any criteria, such as department number or years of service? Several pieces of documentation are often provided to help the programmer understand the problem. Documentation consists of all the supporting paperwork for a program; it might include items such as original requests for the program from users, sample output, and descriptions of the data items available for input. Understanding the problem might be even more difficult if you are writing an app that you hope to market for mobile devices. Business developers are usually approached by a user with a need, but successful developers of mobile apps often try to identify needs that users aren’t even aware of yet. For example, no one knew they wanted to play Angry Birds or leave messages on Facebook before those applications were developed. Mobile app developers also must consider a wider variety of user skills than programmers who develop applications that are used internally in a corporation. Mobile app developers must make sure their programs work with a range of screen sizes and hardware specifications because software competition is intense and the hardware changes quickly. Fully understanding the problem may be one of the most difficult aspects of programming. On any job, the description of what the user needs may be vague—worse yet, users may not really know what they want, and users who think they know frequently change their minds after seeing sample output. Planning the Logic: The heart of the programming process lies in planning the program’s logic. During this phase of the process, the programmer plans the steps of the program, deciding what steps to include and how to order them. You can plan the solution to a problem in many ways. The two most common planning tools are flowcharts and pseudocode. Both tools involve writing the steps of the program in English.Programmers refer to planning a program as “developing an algorithm.” An algorithm (see the end of the section for the meaning) is the sequence of steps or rules you follow to solve a problem.In addition to flowcharts and pseudocode, programmers use a variety of other tools to help in program development. One such tool is an IPO chart, which delineates input, processing, and output tasks. Some object-oriented programmers also use TOE charts, which list tasks, objects, and events. Storyboards and UML are frequently used in interactive, object-oriented applications. The programmer shouldn’t worry about the syntax of any particular language during the planning stage, but should focus on figuring out what sequence of events will lead from the available input to the desired output. Planning the logic includes thinking carefully about all the possible data values a program might encounter and how you want the program to handle each scenario. Coding the Program: After the logic is developed, only then can the programmer write the source code for a program. Hundreds of programming languages are available. Programmers choose particular languages because some have built-in capabilities that make them more efficient than others at handling certain types of operations. Despite their differences, programming languages are quite alike in their basic capabilities—each can handle input operations, arithmetic processing, output operations, and other standard functions. The logic developed to solve a programming problem can be executed using any number of languages. Only after choosing a language must the programmer be concerned with proper punctuation and the correct spelling of commands—in other words, using the correct syntax. Use a Compiler or Interpreter to Translate the Program into Machine Language: Even though there are many programming languages, each computer knows only one language—its machine language, which consists of 1s and puters understand machine language because they are made up of thousands of tiny electrical switches, each of which can be set in either the on or off state, which is represented by a 1 or 0, respectively. Languages like Java or Visual Basic are available for programmers because someone has written a translator program (a compiler or interpreter) that changes the programmer’s English-like high-level programming language into the low-level machine language that the computer understands.When you learn the syntax of a programming language, the commands work on any machine on which the language software has been installed. However, your commands then are translated to machine language, which differs in various computer makes and models. If you write a programming statement incorrectly, the translator program doesn’t know how to proceed and issues an error message identifying a syntax error. Although making errors is never desirable, syntax errors are not a programmer’s deepest concern, because the compiler or interpreter catches every syntax error and displays a message that notifies you of the problem. The computer will not execute a program that contains even one syntax error. Typically, a programmer develops logic, writes the code, and compiles the program, receiving a list of syntax errors. The programmer then corrects the syntax errors and compiles the program again. Correcting the first set of errors frequently reveals new errors that originally were not apparent to the compiler. Testing the Program: A program that is free of syntax errors is not necessarily free of logical errors. A logical error results when you use syntactically correct statements but the program doe not produce the intended results. Once a program is free of syntax errors, the programmer can test it—that is, execute it with some sample data to see whether the results are logically correct. The process of finding and correcting program errors is called debugging. You debug a program by testing it using many sets of data. Selecting test data is somewhat of an art in itself, and it should be done carefully Putting the Program into Production: Once the program is thoroughly tested and debugged, it is ready for the organization to use. Putting the program into production might mean simply running the program once, if it was written to satisfy a user’s request for a special list. However, the process might take months if the program will be run on a regular basis, or if it is one of a large system of programs being developed. Perhaps data-entry people must be trained to prepare the input for the new program, users must be trained to understand the output, or existing data in the company must be changed to an entirely new format to accommodate this program. Conversion, the entire set of actions an organization must take to switch over to using a new program or set of programs, can sometimes take months or years to accomplish. Maintaining the Program: After programs are put into production, making necessary changes is called maintenance. Maintenance can be required for many reasons: for example, because new tax rates are legislated, the format of an input file is altered, or the end user requires additional information not included in the original output specifications. Frequently, your first programming job will require maintaining previously written programs. When you maintain the programs others have written, you will appreciate the effort the original programmer put into writing clear code, using reasonable variable names, and documenting his or her work. When you make changes to existing programs, you repeat the development cycle. That is, you must understand the changes, then plan, code, translate, and test them before putting them into production. If a substantial number of program changes are required, the original program might be retired, and the program development cycle might be started for a new program.Al?nt?: Cesur Baransel, Dünyada ?nde Gelen Bilgisayarc?lar, Türkiye Bili?im Ansiklopedisi, pp. 333-343, Papatya Yay?c?l?k, ?stanbul, 2006.Harezmli Muhammed (780(?) - 850)M.S. 830 y?llar?nda Abbasi halifesi Memun, Harezmli Muhammed’e a?a??daki buyru?u verir:“Yaln?zca en kolay ve en gerekli olan aritmeti?i kullanarak, cebir ve mukabele kurallar? ile hesaplama üzerine k?sa bir kitap yaz. ?yle ki bu kitap, miras payla??m?nda, zek?t hesaplamada, ticari anla?malarda, kanallar?n kaz?lmas?nda, arazilerin ?l?ülmesinde ve benzer di?er i?lemlerde kolayl?kla kullan?labilsin”. Harezmli bunun üzerine Al Kitab-ül Muhtasar Fi Hesab Al-Cebr Ve’l Mukabele adl?, onlu say? sistemi ve denklemler yoluyla sorun ??zme y?ntemlerinin ilk kez anlat?ld??? ünlü kitab?n? yazar. Tarihteki ilk cebir kitab? olarak kabul edilen bu kitap matematik tarihindeki en ?nemli yap?tlardan birisi olup ?ngilizce’deki “algebra” s?zcü?ü kitab?n ad?ndaki “al-cebr” s?zcü?ünden gelmektedir. Kitab?n matematik tarihindeki ?nemi ?zellikle matematik tarihi konulu kitaplarda ayr?nt?s? ile yer almaktad?r. Ancak bu kitap bilgisayar bilimleri a??s?ndan da ayr? bir ?neme sahiptir. Harezmli, kitab?n geni? kitleler taraf?ndan kullan?labilmesini sa?lamak üzere günlük ya?amda ??zülmesi gereken sorunlar? sistemli olarak s?n?flam?? ve her sorun türü i?in ge?erli genel ??züm bi?imleri olu?turmu?tur. Her ??züm, sonlu say?da ve iyi tan?mlanm?? ad?mlar i?eren re?eteler bi?iminde okuyucuya sunulmu? ve b?ylece matematik?i olmayan ki?iler taraf?ndan da etkinlikle kullan?labilmesi sa?lanm??t?r. Genel ama?l? bir ??zümün, birbirini izleyen ad?mlar bi?iminde ve her ad?m?n ??züm re?etesini uygulayan ki?inin en kü?ük bir duraksamaya dü?mesine olanak b?rakmayacak yal?nl?kta ve kesinlikte tan?mlanmas? y?ntemi Harezmli’nin bulu?udur. Bu y?ntem Harezmli’nin ad?yla an?lmakta olup bat? dillerinde “algorismus” “algorism”, “algorithme”, “algorithm” gibi bi?imlerde kullan?lmaktad?r. Harezmli kitab?n? o zaman?n bilim dili olan Arap?a yazm??t?. Kitap “Liber Algebre et Almochabolae” ba?l??? ile 1183 y?l?nda ?spanya’da ilk kez Latince’ye ?evrilirken, Arap?a’da “Ebu Cafer Muhammed bin Musa Al-Harezm?” olarak ge?en yazar ad?, “Mahmed Moysi Alguarizmi” olarak aktar?lm??t?r. Y?ntemin bat? dillerindeki bi?iminin kayna?? bu Latince tercümedeki “Alguarizmi” soyad?d?r (Bu ad Avrupa’da ?e?itli kaynaklarda Al-Quarizmi, Al-Kuarithmi ve Algoritmi olarak da ge?er. Arap?a sesbirimlerinin ?evriyaz?m?nda h?r?lt?l? h’n?n kh, g ya da q’ye, peltek z’nin th’ye d?nü?mesi s?k g?rülür). Osmanl?lar, Harezmli’nin y?ntemini “Harezmiyet” yani “Harezmli Yolu” olarak adland?rm??lard?r. Günümüz Türk?e’sinde ise bu kavrama kar??l?k olarak “Harezmli Yolu” ya da k?saca “Harezmlice” s?zcü?ü kullan?lmaktad?r. Harezmli, Bat? kaynaklar?nda ?o?unlukla Arap ve bazen de Acem k?kenli olarak an?lmaktad?r. Baz? kaynaklarda ise milliyetinden s?z edilmeksizin ?slam dü?ünürü ve matematik?isi olarak yer al?r. Harezmli’nin ya?ad??? d?nem Abbasi imparatorlu?unun (749-1258) en parlak d?nemidir. D?nemin halifesi Memun (813-833) ve babas? Harun Re?id do?u Hindistan’dan ?spanya’ya dek uzanan ülke s?n?rlar? i?erisindeki bilim adamlar?n? Ba?dat’ta kurduklar? “Dar-?l Hikme (Bilgeler Evi)” adl? o zaman?n ara?t?rma merkezinde bir araya getirerek ?al??malar?na destek olmu?lar ve burada ?al??anlara maa? ba?lam??lard?. Harezmli do?up büyüdü?ü yer olan Harezm’den 810 y?llar?nda, otuz ya?lar?nda iken, ?a?r? üzerine Ba?dat’a gelerek Dar-?l Hikme’nin ba??na ge?mi? ve 850 y?l?nda ?lümüne de?in Ba?dat’da ya?am??t?r. Dar-?l Hikme 800-1100 y?llar? aras?nda Dünya’n?n bilim ve kültür merkezi olma ?zelli?ini korumu?tur. Ancak bundan ?nceki Emevi d?neminde, yakla??k 670-740 y?llar? aras?ndaki 70 y?ll?k d?nemde Araplar ve Türkler aras?nda sürekli sava?lar ya?anm??t?r. Buhara’n?n 673’de ku?at?lmas? ile ba?layan ve Baykent, Talkan ve Curcan katliamlar?na sahne olan bu d?nemde Aral G?lü’nün alt?ndaki Harezm b?lgesi Emevilerin Horasan valisi Kuteybe taraf?ndan i?gal edilir. ??gal s?ras?nda ya?anan talan ve y?k?m ve yaz?l? dil bilenler d?hil tüm bilginlerin k?l??tan ge?irildi?i olaylar Harezmli ünlü Türk bilgini Biruni taraf?ndan ayr?nt?s?yla yaz?lm??t?r. Bu olaylardan ancak bir yüz y?l kadar sonra kendisine El-Harezm? (Harezmli ki?i) dedirten, Türk?e ?evirmenlik yapan ve Harezm’de do?up yeti?en birisinin Arap k?kenli olma olas?l??? pek yoktur. Dolay?s?yla cebirin babas?n?n ve algoritma kavram?n?n yarat?c?s?n?n Türk olma olas?l??? ?ok daha yüksektir. OCTAVE GUIOctave’s GUI looks quite similar to MATLAB’s GUI. The left side has three panels:File Browser: You can browse through the files in a working directory and change the names. You can run an .m file by clicking on the file. The file opens in the Editor window and can be run from there. Workspace: It stores the variables names, values, and their properties like types and sizes. It is useful for developers to visualize the variables and their contents. The meaning of variables and their values, sizes, etc. is illustrated in subsequent chapters. Command History: It stores the commands used in an Octave session. A command can be run by simply clicking it in command window. It is then executed at Octave command prompt. All three panes are optional and can be closed down for a session by clicking the cross sign in the upper-right. On the right side, there is a pane named Command Window. The bottom part of the Command window includes three tabs: Command window Editor Documentation The Command window takes input one line at a time. The Editor window is used to write an “.m script file” that can then be executed. The Documentation window can be used to read documentation and seek help to learn more about commands. Octave has an extensive documentation that enables a beginner to learn Octave with nothing but a command line. It also helps an experienced user who can seek help in using less common commands. Sometimes you’ll need to obtain a clear screen, which is what the clc command does.When you start an Octave session, you can work in an interactive session in the sense that the Octave prompt >> waits for you to input a command, which will be executed as soon as you press the Enter key at the end of command. The Octave command prompt presents a full-featured interactive command-line commonly called REPL (read-eval-print loop). The interactive shell of the Octave programming language is commonly called REPL because it: Reads what a user types Evaluates what it reads Prints out the return value after evaluation Loops back and does it all over again Working with FilesApart from working on Octave REPL, you can write multi-line programs using the built-in text editor in Octave and run the program. This can be created by typing edit helloagain at the Octave command prompt. A new file called helloagain.m will be created in a folder/directory in which the present session of Octave is running. Alternatively, the program can also be created in the editor by clicking on the lowermost part of the Command Window, which has an option named Editor. This opens a blank editor window in which the helloagain.m code can be written manually. You can then save the file using Ctrl+S. Note that all Octave script files are saved with an .m extension. You can open the existing file by navigating to the appropriate folder and choosing the file in the explorer. disp("\nHello World!\n") disp("Hello again\n")Listing. The helloagain.m FileThe \n character in the string input is used to print a newline character, which simply adds a paragraph return and prints the next characters on a new line. The disp() function prints the string at the command prompt. You have many options for running an Octave file: You can simply type the name of file (without the extension) at the Octave command prompt. For example, by typing helloagain.From the Editor menu, you can click on Run and choose Save File and Run.You can also choose to click the given key combination. It prompts you to save the file if the script file is being run for the first time. You can choose to save the file at a chosen destination within the local computer’s storage.In any case, the output is displayed at the command prompt, unless graphical output is directed to a graphical terminal. These two methods of working with Octave (using REPL and using files) each has its own merits and usage. Interactive sessions are best for quickly checking for a small part of complex code. Files are best with a project involving detailed calculations and are linked with one another to perform a computational task.Using the WorkspaceA workspace is the space in the memory reserved for objects in the Octave session. All the objects used in calculations are displayed. This is usually placed as the second option in the left panel of the main Octave session window. The command clear clears all global and local variables in the workspace and makes it fresh, just as when an Octave session is initially launched.If the semicolon symbol ; is used at the end of a command, the output is not displayed upon the execution of the command. This is useful when you expect too much output would be displayed. For example, when you are dealing with a multitude of data points, say a million data points, it would be pointless to invest time and computer memory in displaying them at Octave’s command prompt. This feature can also be used within Octave scripts, when you don’t want to print a particular output at the command prompt.Octave as a CalculatorIn its simplest form, Octave works as a calculator with mathematical operators like multiplication (*), division (/), addition (+), subtraction (-), and exponentiation (^). The following code illustrates this behavior: >> 3+5 ans = 8 >> 3.0+5.0 ans = 8 >> 3.1+5.0 ans = 8.1000 >> 2-3 ans = -1 >> 3.0*5 ans = 15 >> 2/3 ans = 0.66667 When a command is entered at the Octave REPL command prompt >>, it is executed and an answer is displayed in the next line as ans =. Ans is a global variable that stores the value of the last executed expression. The commands written at Octave REPL are called expressions and are evaluated by REPL. A number of physical constants are defined as follows: pi, e (Euler’s number), i and j (the imaginary number -1 ), inf (infinity), and NaN (not a number, which results from undefined operations such as Inf/Inf). >> pi ans = 3.1416 >> e ans = 2.7183 >> i ans = 0 + 1i >> j ans = 0 + 1i >> Inf/Inf ans = NaNA number of built-in mathematical functions exist in Octave. A few of the more common ones are: Absolute value abs() Natural logarithm log()Base-10 logarithm log10() Trigonometric functions sin(), cos(), and tan(). Arguments are taken in radians.Inverse-trigonometric functions asin(), acos(), and atan().Using VariablesUntil now, we have been feeding numbers into Octave REPL with on-the-spot evaluation. Alternatively, you can designate a memory location where values are stored and this memory location can be known by a name for ease of usage. Such a programming construct is known as a variable.To store values temporarily, you use variables that store the value at a particular memory location and address it with a symbol or set of symbols (called strings). For example, you can store the value of 1/10*pi as a variable a and then use it in an equation: >> a=1/10*pi a = 0.31416 >> a?2 + 10* sqrt(a) ans = 5.7037 The symbol = works as an assignment operator because it assigns the value on the right side to the variable name on the left side. Its behavior is markedly different than its mathematical counterpart (which checks the equality of its right side and left side). Multiple assignments can be performed using the comma (,) operator. Also if you do not want to produce results on-screen, you can suppress this by using the ; operator. Try the following commands: >> a1 = 1, a2 = 10, a3 = 100 >> a1 = 1, a2 = 10, a3 = 100; >> a1 = 1; a2 = 10; a3 = 100;While assigning data to a variable, it is important to understand that data can be defined as a variety of objects defined by a data type, as follows: Logical: This type of data stores boolean values 1 or 0. Boolean values can be operated on by boolean operators, like AND, OR, XOR, etc. Char: This type of data stores alphabetic characters and strings (groups of characters written in a sequence). Int8, int16, int32, and int64: This type of data is stored as integers within 8 bits, 10 bits, 32 bits, and 64 bits. The size of the integer is given by its bit counts. Both logical and char are 1 byte (8 bits) wide. uint8, uint16, uint32, and uint64: This type of data stores unsigned integer data in 8, 16, 32, and 64 bits. double, single: This type of data is stored as double and single precision floating types, respectively. Decimal numbers are represented by floating point data types. Single precision occupies 4 bytes (32 bits) and double precision occupies 8 bytes (64 bits) to store the floating point numbers. CONTROL STRUCTURESThe normal flow of control in an Octave script is sequential, i.e. each program statement is executed in sequence, one after the other.If all of our programs featured only sequential control flow they would be limited in their power. To write more complex and powerful programs we need to make use of programming constructs that alter this normal control flow. If StatementOne type of programming construct is the conditional statement. The control flow of a conditional statement is illustrated below. 864870152400In this example there are two possible paths through the program, involving execution of different statements. Which path is taken depends on the result of applying a test condition. Enter these statements and save them as a script m-file: a = input('Enter a number:'); if (a >= 0) root = sqrt(a); disp(['Square root = ' num2str(root)]); else disp(['Number is negative and there is no square root']); endPay particular attention to the alternative paths of execution that the program can take depending on the result of the comparison (a >= 0). This comparison corresponds to the condition box in above figure. The two statements after the if will be executed only if the condition is true. The statement after the else will be executed if the condition is false. After one of these two paths has been taken control will resume immediately after the end statement. Note that the if and end statements are both compulsory and should always come in pairs. The else statement is optional and if omitted the program execution path will jump to after the end statement if the condition is false.A list of common comparison (or relational) operators: Equal to: == Not equal to:~= Greater than: >Less than: <Greater than or equal to: >= Less than or equal to: <= There are also the common logical operators for combining the results of different comparisons. ~ NOT && AND (scalar short-circuit operation) & AND (scalar/array operation) || OR (scalar short-circuit operation) | OR (scalar/array operation) Most of these operators are fairly intuitive. However, note the distinction between & and && (and likewise between | and ||). The & and | operators perform AND and OR operations respectively. They will evaluate the expressions on both sides of the operator and return a true or false value depending on whether both (&) or either (|) of them evaluated to true.These operators will work with either scalar (i.e. single value) logical expressions or array expressions (i.e. that evaluate to an array of true/false values). The only restriction is that Octave must be able to match the expressions on either side of the operator. Either both should be scalars, both should be arrays of the same size, or one should be an array and the other a scalar (More on arrays later).The && and || operators perform the same AND and OR operations, but using what is known as a short-circuiting behavior. This means that, if the result of the overall AND/OR operation can be determined from the left-hand expression alone, then the right-hand expression will not be evaluated. For example, if the left-hand expression of an AND operation is false then the result of the AND will also be false, regardless of the value of the right-hand expression. Therefore, the advantage of short-circuiting is that unnecessary operations are not performed. However, note that && and || can only be used with scalar values, not arrays.There are three different operators in the following condition: ==, && and >. In what order would MATLAB evaluate them? An expression containing multiple operators is evaluated using the rules for operator precedence. ... if gender == 'm' && calories > 10+2*75 ...Read about operator precedence using help and doc commands. Brackets have the highest precedence. It is a good idea to include them to make our code easier to understand and less prone to errors. Sometimes we may have many if statements which all use conditions based on the same variable. It is not incorrect to use if statements in such cases, but it can lead to a large number of consecutive if statements in our code, making it harder to read and more prone to errors. In this case, it is preferable to use a switch statement. The switch statement offers an easy way of writing code where the same variable needs to be checked against a number of different values. switch day case 1 day_name = 'Monday'; case 2 day_name = 'Tuesday'; case 3 day_name = 'Wednesday'; case 4 day_name = 'Thursday'; case 5 day_name = 'Friday'; case 6 day_name = 'Saturday'; case 7 day_name = 'Sunday'; otherwise day_name = 'Unknown'; endNote that the switch statement is used only for equality tests – we cannot use it for other types of comparison (e.g. >, <, etc.). In the above example the switch expression was compared to a single value in each case. It is possible to compare the expression to multiple values by enclosing them within curly brackets and separating them by commas. The corresponding statements are executed if any of the values are matched. This is equivalent to an if statement with multiple equality tests combined using a || operator. switch day case {1,2,3,4,5} day_name = 'Weekday'; case {6,7} day_name = 'Weekend'; otherwise day_name = 'Unknown'; endUsing If Statements EffectivelyFirst, we will implement the switch command using if-else statements only. We will provide multiple solutions for this problem, discussing the efficiency of each one. Solution a: a = input('Enter a number for day:'); strA = num2str(a); if (a == 1) disp(['Day ' strA ' is weekday']); end if (a == 2) disp(['Day ' strA ' is weekday']); end if (a == 3) disp(['Day ' strA ' is weekday']); end if (a == 4) disp(['Day ' strA ' is weekday']); end if (a == 5) disp(['Day ' strA ' is weekday']); end if (a == 6) disp(['Day ' strA ' is weekend']); end if (a == 7) disp(['Day ' strA ' is weekend']); endAlthough this program works correctly for proper values, it does not provide an error message if the user enters a number like -1 or 9. The following solution fixes this problem. Note that we cannot say 'Unknown day' using only a simple comparison. Solution b: Solving the "unknown" problem a = input('Enter a number for day:'); strA = num2str(a); sB = ['Day ' strA ' is unknown‘]; if (a == 1) sB = (['Day ' strA ' is weekday']); end if (a == 2) sB = (['Day ' strA ' is weekday']); end if (a == 3) sB = (['Day ' strA ' is weekday']); end if (a == 4) sB = (['Day ' strA ' is weekday']); end if (a == 5) sB = (['Day ' strA ' is weekday']); end if (a == 6) sB = (['Day ' strA ' is weekend']); end if (a == 7) sB = (['Day ' strA ' is weekend']); end sB This program has a different logic from the previous one. It does not display a message immediately after making comparisons. Instead, it prepares a message whis says the “Day is unknown”. If the users enters a valid value, this message is updated. Otherwise, the “Day is unknown” message stays as it is. At the end of the program sB is displayed, either with its original or updated content, depending on the value that the user has entered.The following solutions uses if statements with multiple equality tests combined using logical OR (||) and logical AND (&&) operators. Solution c: a = input('Enter a number for day:'); strA = num2str(a); if (a == 1 || a == 2 || a == 3 || a == 4 || a == 5) disp(['Day ' strA ' is weekday']); end if (a == 6 || a == 7) disp(['Day ' strA ' is weekend']); end if (a ~= 1 && a ~= 2 && a ~= 3 && a ~= 4 && a ~= 5 && a ~= 6 && a ~= 7) disp(['Day ' strA ' is unknown']); endThis solution is better since it reduces the number of if statements down to three. However the condition of the last if statement is unnecessarily cumbersome. A much better alternative exists, as seen in the following solution.Solution d: a = input('Enter a number for day:'); strA = num2str(a); if (a == 1 || a == 2 || a == 3 || a == 4 || a == 5) disp(['Day ' strA ' is weekday']); else if (a == 6 || a == 7) disp(['Day ' strA ' is weekend']); else disp(['Day ' strA ' is unknown']); end endThis solution offers the following improvements over the previos ones.Faster execution with less number of comparisons executed, since number of if stetments are reduced from 7 to 3.The long logical condition for the"unknown day " is no longer necessary and therefore eliminated. Below, we draw the flowchart for this solution to see how elimination become possible. WEEKDAYWEEKENDUNKNOWNa == 1 ||a == 2 ||a == 3 ||a == 4 ||a == 5TrueFalseHere we know that the condition is FALSE ?e: ~(a==1||a==2||a==3||a==4||a==5) is TRUE So: (a~=1 &&a ~= 2&&a ~= 3&& ~= 4&&a ~= 5) a == 6 ||a == 7TrueFalseNow we know ( a~=1 && a ~= 2 && a ~= 3 && a~= 4 && a ~= 5 )AND( a~=6 && a ~=7 ) Now we introduce the recommended solution.This solution uses the so-called elseif statement (not else if ).The elseif statement is easy to understand and is more similar to switch statement. However, note that,The alternative cases can have complex conditions and each if does not have to have its own end statement. In other words, an elseif statement has a single else and a single end part.The last (and only) else corresponds to otherwise in the switch statement.Solution e: The recommended solution a = input('Enter a number for day:'); strA = num2str(a); if (a == 1 || a == 2 || a == 3 || a == 4 || a == 5) disp(['Day ' strA ' is weekday']); elseif (a == 6 || a == 7) disp(['Day ' strA ' is weekend']); else disp(['Day ' strA ' is unknown']); end You should be careful when writing conditions for the if-statements. You may find yourself writing conditions impossible to satisfy, i.e., conditions that never can be true. The following exercise illustrates this point.Assume that you write a program where user enters two numbers and program selects the greatest one. This is a fairly easy program and can be coded as follows: n1 = input('Enter the first number:'); n2 = input('Enter the second number:'); if (n1 == n2) disp('Numbers are equal'); end if (n1 > n2) disp('The first number is greater than the second number'); end if (n1 < n2) disp('The first number is less than the second number'); end The logic is easy to explain: There are only 3 possible cases for 2 numbers: Numbers can be equal to each other, or the first number can be greater than the second number or the first number can be less than the first number. Furthermore, these cases are mutually exclusive, meaning that only one of them can be true for a given pair of numbers.In the program, each case is handled by a seperate if statement. Now, repeat the exercise for 3 numbers. How many possible cases are there? For 4 numbers? For 5 numbers?The most important question is this: When writing the program, should you simply enumerate all possible cases first and then write an if statetement for each one?The short answer is no. Such a blind approach can easily lead to a situation where a lot of unnecessarily written if statements sitting there doing nothing but cluttering your code and slowing down your program. Consider the case of three numbers. Without too much thinking, we can use a simple logic: Since any two number can be related in 3 possible ways (>, ==,<), 3 numbers can be related in 33=27 possible ways. This logic can be drawn partially as follows:A > CA == CA < CA > CA == CA < CA > CA == CA < CB > CB == CB < CA == BA < BA > BThere are 3 x 3 x 3=27 possible cases for 3 numbers.There are 3^6=729 possible cases for 4 numbers.There are 3^10=59049 possible cases for 5 numbers.We have drawn only 1/3 of the possible cases, which is sufficient to show that the above logic is simply wrong! Let’s write the code for the first two branches in the above diagram: A = input('Enter the first number:'); B = input('Enter the second number:'); C = input('Enter the third number:'); if (A == B && B == C && A == C) disp('Numbers are equal to each other'); end if (A == B && B == C && A > C) disp(???) ; end The second if can never evaluate to true. Why? Consider the case where A is equal to B. Then, if B is equal to C, A and C must be equal to each other (because A and C both are equal to the same number B). It is clear that, in that case (A > C) can never be true. Since all conditions are tied together with logical AND operator, three numbers that can make the whole expression true simply do not exist. Here, an impossible case is coded. The programmer has written unnecessary code, the computer check this statement every time it runs and program becomes larger. Avoid these kind of mistakes in your programs and by learning that simply handling combinatorial cases one by one does not necessarily yield logically correct results.Think well before writing if-else conditions. You may be writing impossible to satisfy conditions.You may be missing some critically important conditions. You may be writing contradictory conditions in different places in code. Do the following self-study excersies to test your understanding of the subject:Exercise 1: User enters 3 numbers from keyboard. Sort these numbers in descending order and solve the "find the greates number" problem after the sort operation. Exercise 2: Write a program that displays the smallest of five input values that may include duplicate values (e.g., 6, 4, 8, 6, 7).Exercise 3: Write a program that inputs a number between 1 and 10 and displays the number with the appropriate two-letter ending (e.g., 1st, 2nd, 3rd, 4th, 5th…).Exercise 4: Write a program that will receive three test scores as input. The program should determine and display their average and the appropriate letter grade based on the average. The letter grade should be determined using a standard 10-point scale (A 90–100; B 80–89.999; C 70–79.999, F 70–69.999)Excersises with solutions:Question 1The ticket price for a concert varies according to the age of the customer. When the person is under 16, the charge is 70 TRY; When the person is 65 or over, the charge is 50 TRY; All others are charged 100 TRY.Given the age of the customer, calculate the ticket price.Draw the flowchart of the solution.Write the Octave code.Solution 1First, try to visualize how your program will work. It should work as follows if the age of the customer is 15: Enter the age of the customer: 15 The ticket price for this customer is 70 TRYIt should work as follows if the age of the customer is 67: Enter the age of the customer: 67 The ticket price for this customer is 50 TRYIt should work as follows if the age of the customer is 42: Enter the age of the customer: 42 The ticket price for this customer is 100 TRYIt is clear that the program should read the age of the customer from the keyboard and display the proper ticket price. Consequently, the program has one input (the age of the customer) and one output (the ticket price).To read the input, you use the input command in Octave.To display the output, you use the disp command in Octave.In order to decide what the ticket price should be, we must consider three cases. These cases are already given in the problem definition, as seen in the following figure. Age166570 TRY100 TRY50 TRY0The simplest solution is to write three if statements, one for each case. The flowchart is shown below:Enter the age of the customer:Age > 65Ticket price is 70 TRYTrueFalseAge < 16Ticket price is 50 TRYTrueFalseage>=16 && age<=65Ticket price is 100 TRYTrueFalseendThe Octave code for this flowchart is: age = input('Enter the age of the customer:'); if (age < 16) disp('Ticket price for this customer is 70 TRY'); end if (age > 65) disp('Ticket price for this customer is 50 TRY'); end if (age >= 16 && age <= 65) disp('Ticket price for this customer is 100TRY'); endAs discussed previously, this is not the recommended solution. Also, suppose that the user enters -5 as the age, or 5000? What should the program do? The following code is a better solution. It only fails when a person older than 130 shows up. age = input('Enter the age of the customer:'); if (age < 16 && age >= 0) disp('Ticket price for this customer is 70 TRY'); elseif (age > 65 && age < 130) disp('Ticket price for this customer is 50 TRY'); elseif (age >= 16 && age <= 65) disp('Ticket price for this customer is 100 TRY'); else disp('Invalid age information is entered'); endNote that, the flowchart for this solution will be different from the one above. Examine the following flowchart and be sure that you understand how the redundant execution of if statements are eliminated.Enter the age of the customer:Ticket priceis 70 TRYFalseTicket priceis 50 TRYTrueage>=16 && age<=65Ticket priceis 100 TRYTrueFalseendage>=0 && age<16Age>65 && age<130TrueFalseInvalid age!Here, the program receives an input value and decides into which predefined interval (0?16, 16?65, 65?130) this value falls into, before taking the necessary action. This mechanism can be used for creating many, seemingly different problems. Do not be fooled by the story presented in the problem. In fact, all these problems are the same. Two of such seemingly different but essentially the same questions are presented in questions 2 and 3.Question 2A company calculates the commission rate for a salesperson, given the amount of sales. When the amount of sales is less than or equal to 2,000 TRY, the commission is 2%. When the amount of sales is more than 2,000 TRY and less than or equal to 4,000 TRY, the commission is 4%. When the amount of sales is more than 4,000 TRY and less than or equal to 6,000 TRY, the commission is 7%.When the amount of sales is more than 6,000 TRY, the commission is 10%.Given the amount of sales, calculate the commission.Draw the flowchart of the solution.Write the Octave code.Solution 2Draw the flowchart and see that how it is similar to the flowchart of the previous problem:Enter the sales amount S:Commission = S * 0.02FalseCommission = S * 0.04TrueS>4000 && S<=6000Commission = S * 0.07TrueFalseendS>=0 && S<=2000S>2000 && S<=4000TrueFalseCommission = S * 0.10Invalid sales amountS > 6000FalseTrueAnd the Octave code is: S = input('Enter the sales amount:'); if (S >= 0 && S <= 2000) disp(['Comission is ' num2str(S*0.02)]); elseif (S > 2000 && S <= 4000) disp(['Comission is ' num2str(S*0.04)]); elseif (S > 4000 && S <= 6000) disp(['Comission is ' num2str(S*0.07)]); elseif (S > 6000) disp(['Comission is ' num2str(S*0.10)]); else disp('Invalid sales amount is entered'); endQuestion 3An admission charge for a music concert varies according to the age of the person. Develop a solution to print the ticket charge given the age of the person. The charges are as follows:Over 55: 10.00 TRY21–54: 20.00 TRY13–20: 15.00 TRY3–12: 5.00 TRYUnder 3: FreeDraw the flowchart of the solution (10 points).Write the Octave code.Solution 3The Octave code is provided below. Draw the flowchart yourself. age = input('Enter the age of the customer:'); if (age >= 0 && age < 3) disp('Ticket for this customer is free'); elseif (age >= 3 && age < 13) disp('Ticket price for this customer is 5 TRY'); elseif (age >= 13 && age < 21) disp('Ticket price for this customer is 15 TRY'); elseif (age >= 21 && age < 55) disp('Ticket price for this customer is 20 TRY'); elseif (age >= 55 && age < 130) disp('Ticket price for this customer is 10 TRY'); else disp('Invalid age information is entered'); endQuestion 4The figure below shows how blood pressure can be classified based on the diastolic and systolic pressures. Write a MATLAB script m-file to display a message indicating the classification based on the values of two variables representing the diastolic and systolic pressures. The two blood pressure values should be read in from the keyboard. 1904104163327Solution 4This problem differs from those above in two respects:It receives two inputs (diastolic pressure and systolic pressure).The decision intervals are more complicated to express programmatically.ABCDFor example consider the High region.When systolic pressure is between 140 and 190 we don’t need to consider the value of the Diastolic pressure. This is the region A in the graph. In region B, the blood pressure is also high. So, we need to expess these two regions separately and tied them together using a logical OR operator (i.e., if values are in ((region A) || (region B)), then the blood pressure is high).Following the same logic for the other regions as well, the Octave code can be written as follows. s = input('Enter the systolic pressure:'); d = input('Enter the diastolic pressure:'); if ( (s > 140 && s <= 190) || %this is region A (d > 90 && d <= 100) ) %this is region B disp('The blood pressure is HIGH'); end if ( (s > 120 && s <= 140 && d > 40 && d <= 90) || (s > 70 && s <= 120 && d > 80 && d <= 90) ) disp('The blood pressure is PRE-HIGH'); end if ( (s > 90 && s <= 120 && d > 40 && d <= 80) || %this is region C (s > 70 && s < 90 && d > 60 && d <= 80) ) %this is region D disp('The blood pressure is IDEAL'); end if (s >= 70 && s <= 90 && d >= 40 && d <= 60) disp('The blood pressure is LOW'); endQuestion 5A company has two types of workers: Workers who get paid according to the number of hours they work each week (H-type) and workers that work for a predefined salary (S-type).Weekly pay for S-type workers is 750 TRY if they work 40 or more hours within the week. If they work less than 40 hours they still get 750 TRY. However, if they work less than 30 hours they will get 700 TRY. H-type workers are paid 12 TRY per hour up to 40 hours. For more than 40 hours, they are paid 18 TRY for each extra hour. Write a solution to compute the weekly pay for a given worker. The data is entered from the keyboard in the following format:Name of the Worker Type of the Worker Hours Worked:--------------------------- -------------------------- --------------------Ahmet Gen? H 35Mehmet Bal S 42 Draw the flowchart of the solution.Write the Octave code.Solution 5Invalid Worker Type!Enter the Name of the worker N:Enter the type of the worker T:Enter the number of hours worked W:Pay 750 TRYFalseTruePay W*12 TRYTrueendT==’S’TrueFalseW>=30TrueFalseT==’H’W>40FalsePay 700 TRYPay 12*40+(W-40)*18 TRYThe flowchart is given above and Octave code can be written as follows: N = input('Enter the Name of the worker: ', 's'); T = input('Enter the type of the worker: ', 's'); W = input('Enter the number of hours worked: '); if (T=='S' && W >= 30) disp(['Pay ' N ' 750 TRY']); end if (T=='S' && W < 30) disp(['Pay ' N ' 700 TRY']); end if (T=='H' && W <= 40) disp(['Pay ' N ' ' num2str(W*12) ' TRY']); end if (T=='H' && W > 40) disp(['Pay ' N ' ' num2str(40*12+(W-40)*18) ' TRY']); end if (T~='H' && T~='S') disp('Invalid worker type!'); endQuestion 6A hotel has a pricing policy as follows: The cost of a room is 100 TRY. If the customer is staying on company business, there is a 20% discount. If the customer is over 60 years of age, there is a 15% discount. If eligible, a customer does not receive both discounts, only the larger one. Given the above rules, print the cost of the room.Draw the flowchart of the solution.Write the Octave code.Solution 6In this problem, the order of logical tests is important. The rules say that there are two types of discount in this hotel, one for people who are on business trip (20%), and the other for people older than 60 (15%). The last rule states that anyone who is both older than 60 and on a business trip does not receive both discounts, only the larger one (that is 20%).In other words, for people on business trip, the age is not important: they always receive the 20% discount, and nothing else. You should check the age only when the 20% discount is not possible.So, the proper flowchart should be drawn as follows:Pay 100 TRYEnter the Age of the worker age:Enter Yes if the customer is on a business trip onB:Pay 80 TRYFalseTrueendonB==’Yes’TrueFalseAge>60Pay 85 TRYThe Octave code is: age = input('Enter the age of the customer:'); onB = input('Enter YES if the customer is on business trip:', 's'); if (onB == 'YES') disp('Customer should pay 80 TRY'); elseif (age > 60) disp('Customer should pay 85 TRY'); else disp('Customer should pay 100 TRY'); endQuestion 7Ay?e needs to buy a present for her best friend. She can buy it online or she can travel by car to buy at the store. The online cost of the item may be different from the cost at the store. Ay?e’s car uses 0.25 TRY worth of gas per Km.She is not sure which would be less expensive considering shipping & handling costs to buy online and gas costs to travel to the store. Write a solution to tell Ay?e which would be the best way to buy the present.Draw the flowchart of the solution.Write the Octave code.Solution 7This problem is extremely simple. Consider the following two examples:You will buy a smart phone. The phone is sold at 1000 TRY at a store 4 Km away. The same phone is also sold at an on-line store for 900 TRY with 10 TRY for cargo expenses. Then, the cost of buying the phone at the store is (1000+4*0.25=1001 TRY). Compare this cost to the cost of buying the phone on-line which is (900+10=910 TRY). In this case, It is clear that you should buy it on-line.You will buy a roller pen. The pen is sold at 10 TRY at a store 2 Km away. The same pen is also sold at an on-line store for 9 TRY with 5 TRY for cargo expenses. Then, the cost of buying the pen at the store is (10+2*0.25=10,50 TRY). Compare this cost to the cost of buying the phone on-line which is (9+5=14 TRY). In this case, it is clear that you should buy it at the store.Examples show that to make the decision, the program needs for values as input:The cost of the item at the storeThe distance to the store in KmThe cost of the item on-lineThe shipping and handling cost (i.e., cargo expenses)The flowchart:Same cost! Enter the price at store storePrice: Enter the distance to store in Km distance: Enter the on-line price onlinePrice: Enter the shipping & handling cost cargo:Buy onlineFalseTrueenddiff > 0TrueFalsediff < 0Buy at store diff = (storePrice + distance * 0.25) - (onlinePrice + cargo)The code: storePrice = input('Enter the price at store: '); distance = input('Enter the distance to store in Km: '); onlinePrice = input('Enter the on-line price: '); cargo = input('Enter the shipping & handling cost: '); diff = (storePrice + distance * 0.25) - (onlinePrice + cargo) ; if (diff > 0) disp('Buy online'); elseif (diff < 0) disp('Buy at the store'); else disp('No difference, buy wherever you want!'); endFor LoopIn addition to conditional statements, the second fundamental type of programming construct that we will consider here is the iteration statement. Iteration statements are intended for use in situations in which one or more operations need to be repeatedly performed a number of times. In computer programming, iteration statements are often known as loop statements. There are two types of iteration statements: for loops and while loops:for loops can be useful when we want to execute some statements a fixed number of times. Consider the following example. This code reads in a number from the user and computes its factorial. % ask user for input n = input('Enter number:'); f = 1; if (n >= 0) for i = 2:n f = f * i; end disp(['The factorial of ' num2str(n) ' is ' num2str(f)]); else disp(['Cannot compute factorial of the number']); endWhile LoopThe second type of iteration statement available in Octave is the while loop. The control flow of a while loop is shown below. First, a condition is tested. If this condition evaluates to false then control immediately passes beyond the while statement. If it evaluates to true then a statement (or sequence of statements) is executed and the condition is retested. This iteration continues until the condition evaluates to false. Therefore, a while loop will execute continually until some condition is no longer met. This type of behavior can be useful when continued loop execution depends upon some computation or input that cannot be known before the loop starts.1664970-30480Consider the following example. This program first generates a random integer between 0 and 9. The Octave randi statement, used in this way, generates a random integer from a uniform distribution between 1 and its argument (in this case, 10), so by subtracting 1 from this we can get a random integer between 0 and 9. The following while loop will iterate whilst the condition guess ~= i is true. In other words, the loop will execute so long as guess is not equal to the random integer i. Since guess is initialized to ?1 before the loop starts, the loop will always execute at least once. Inside the loop, a number is read from the user, and an if statement is used to display an appropriate message depending upon whether the guessed number is correct. The program will continue asking for guesses until the correct answer is entered. i = randi(10) ?1; % random integer between 0 and 9 guess = ?1; while (guess ~= i) guess = input('Guess a number:'); if (guess == i) disp('Correct!'); else disp('Wrong, try again ...'); end endBreak and Continue StatementsAnother way of altering the control flow of a program is to use jump statements. The effect of a jump statement is to unconditionally transfer control to another part of the program. Octave provides two different jump statements: break and continue. Both can only be used inside for or while loops. The effect of a break statement is to transfer control to the statement immediately following the enclosing control structure. Consider the following code. total = 0; while (true) n = input('Enter number: '); if (n < 0) disp('Finished!'); break; end total = total + n; end disp(['Total = ' num2str(total)]);This piece of code reads in a sequence of numbers from the user. When the user types a negative number the loop is terminated by the break statement. Otherwise, the current number is added to the total variable. When the loop terminates (i.e. a negative number is entered), the value of the total variable, which is the sum of all of the numbers entered, is displayed. The continue statement is similar to the break statement, but instead of transferring control to the statement following the enclosing control structure, it only terminates the current iteration of the loop. Program execution resumes with the next iteration of the loop. total = 0; for i = 1:10 n = input('Enter number: '); if (n < 0) disp('Ignoring!'); continue; end total = total + n; end disp(['Total = ' num2str(total)]);A sequence of numbers is again read in and summed. However, this time there is a limit of 10 numbers, and negative numbers are ignored. If a negative number is entered, the continue statement causes execution to resume with the next iteration of the for loop.Nested LoopsAny of the control structure statements we have covered so far can be nested. This simply means putting one statement inside another one. n = input('Enter number: '); while (n >= 0) f = 1; for i = 2:n f = f ? i; end disp(f); n = input('Enter number: '); endHere, we have a for loop nested inside a while loop. The while loop reads in a sequence of numbers from the user, terminated by a negative number. For each positive number entered, the for loop computes its factorial, which is then displayed.Some ExcersisesQuestion 1A shop is having a five-day sale. Each day, starting on Monday, the price will drop 10% of the previous day’s price. Example: If the original price of a product is 20.00 TRY;On Monday the sale price would be 18.00 TRY (10% less than the original price). On Tuesday the sale price would be 16.20 TRY (10% less than Monday). On Wednesday the sale price would be 14.58 TRY (10% less than Tuesday). On Thursday the sale price would be 13.12 TRY (10% less than Wednesday).On Friday the sale price would be 11.81 TRY (10% less than Thursday). Write the Octave code that will calculate and list the price of an item for each and every one of the five days, given the original price.The above list is an example only. Your code should work with any original price of a product that the user enters.Solution:Remember the solution to the factorial problem, which was given previously as follows: n = input('Enter number:'); f = 1; for i = 2:n f = f * i; end disp(['The factorial of ' num2str(n) ' is ' num2str(f)]);The solution to the problem is similar, but much simpler: We always multiply with 0.9: n = input('Enter the price:'); for i = 1:5 n = n * 0.9 ; disp(['The price at day ' num2str(i) ' is ' num2str(n) ' TRY' ]); endThe above solution is sufficient for getting full marks. But if you want to display the day name properly, you modify the code as follows: n = input('Enter the price:'); for i = 1:5 n = n * 0.9 ; if (i==1) dayName = 'Monday' ; end if (i==2) dayName = 'Tuesday' ; end if (i==3) dayName = 'Wednesday' ; end if (i==4) dayName = 'Thursday' ; end if (i==5) dayName = 'Friday' ; end disp(['The price on ' dayName ' is ' num2str(n) ' TRY' ]); endQuestion 2A clock simulator will be written. The program will display the following output: 0:0:0 0:0:1 0:0:2 . . 23:59:59Draw the flowchart for this program.Write Octave code.Solution:The flowchart:The code: for hours = 0 : 23 for minutes = 0 : 59 for seconds = 0 : 59 disp ([ num2str(hours) ":" num2str(minutes) ":" num2str(seconds)]) ; end end endQuestion 3Write an Octave program that reads a sequence of numbers from the user. User may enter a negative value, or a positive value, or zero.When the user enters zero the loop is terminated. Otherwise, the negative and positive numbers are summed up separately. When the loop terminates, the average of all negative numbers and the average of all positive numbers are displayed separately. For example: Enter a number: -5 Enter a number: -15 Enter a number: 3 Enter a number: 12 Enter a number: 8 Enter a number: 4 Enter a number: -10 Enter a number: 0 Average of negative numbers: -10 % -30/3 = -10 Average of positive numbers: 6.75 % 27/4 = 6.75Solution:We have solved half of this problem previously as follows: total = 0; while (true) n = input('Enter number: '); if (n < 0) disp('Finished!'); break; end total = total + n; end disp(['Total = ' num2str(total)]);The above solution to takes the sum of numbers entered and stops when a negative number is entered. For the exam question, we need to sum up negative and positive numbers separately. Also, we need to count how many positive and negative numbers are entered to be able to calculate the average. The solution is as follows: totalPositive = 0; countPositive = 0; totalNegative = 0; countNegative = 0; while (true) n = input('Enter number: '); if (n == 0) disp('Finished!'); break; end if (n > 0) totalPositive = totalPositive + n; countPositive = countPositive + 1; end if (n < 0) totalNegative = totalNegative + n; countNegative = countNegative + 1; end end disp (['Average of Negative Numbers ' num2str(totalNegative/countNegative)]); disp (['Average of Positive Numbers ' num2str(totalPositive/countPositive)]);Question 4Write a program to print a multiplication table.At the start, it should ask the user which table to print. After asking which table the user wants, ask her how high the table should go.The output should look something like this, if the user enters 7 and 12: Note that this is only an example. Your code should also work with other numbers such as 12, 18 or 120, 9. Which multiplication table would you like? 7 How high do you want to go? 12 Here's your table: 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70 7 x 11 = 77 7 x 12 = 84Solution:The solution is elementary, requiring only a single for loop: n = input(' Which multiplication table would you like? '); m = input(' How high do you want to go? '); disp ('Here is your table: ') ; for i=1:m disp([num2str(n) ' x ' num2str(i) ' = ' num2str(n*i)]); endQuestion 5Read from keyboard the current population of a city, and a number representing the rate at which the population is increasing per year. Calculate the number of years it will take for the population of the city to double, assuming the present rate of growth remains constant.Example: Assume a population of 1,500,000, and 2 percent population increase rate are given for a city. In that case, the population of the city will be 1,530,000 next year. Then your code should calculate after how many years the population will be 3,000,000 in this city. Solution:The code requires a single while loop: p = input(' What is the current population? '); r = input(' What is the annual population increase rate? '); y = 0 ; k = p ; while (k < 2*p) y = y + 1; k = k + k * r ; disp([' After ' num2str(y) ' years population will be: ' num2str(k)]); end ARRAYSUntil now, we have considered storing only one value as a variable. However, there can be situations when a set of elements require similar processing. Then it would be wise to store them as an ordered set instead of creating separate variables for each data point. Octave defines an object named Array that can store a sequential set of elements. When you declare an array, you declare a structure that contains multiple data items; each data item is one element of the array. Each element has the same data type, and each element occupies an area in memory next to, or contiguous to, the others. You can indicate the number of elements an array will hold (the size of the array) when you declare the array along with your other variables and constants. Each array element is differentiated from the others with a unique index, which is a number that indicates the position of a particular item within an array. All array elements have the same group name, but each individual element also has a unique index.2117725207010 prices[1] = 25.00 prices[2] = 36.50 prices[3] = 47.99Arrays can be defined by simply enclosing elements in square brackets and separating them by comma operators or whitespace. For example: >> a1 = [1,2,3] a1 = 1 2 3 >> a2 = [1 2 3] a2 = 1 2 3 >> a = [1 0 0 3 2 1 3 0 1 5 3 2 1] % defined an array a = 1 0 0 3 2 1 3 0 1 5 3 2 1 >> a(1) % first element ans = 1 >> a(10) % tenth element ans = 5The semicolon ; operator sends the element in the next row instead of the next column. This way, a 2D or 3D array can be created. >> a3 = [1;2;3] a3 = 1 2 3The comma/whitespace operator will separate elements in the same row and ; will define the element in the next column. >> a = [1 2 3;4 5 6] % defining a two dimensional array a = 1 2 3 4 5 6 >> a(1,2) % element in row 1 and column 2 ans = 2 >> a(2,1) % element in row 2 and column 1 ans = 4 >> a(2,2) % element in row 2 and column 2 ans = 5 >> a(2,4) % element in row 2 and column 4 error: a(_,4): but a has size 2x3The elements of an array can have any data type. For Loops for 1D Arrays (Vectors)Consider an application requested by a company’s human resources department to produce statistics on employees’ claimed dependents. The department wants a report that lists the number of employees who have claimed 0, 1, 2, 3, 4, or 5 dependents. (Assume that you know that no employees have more than five dependents.) Without using an array, you could write this application that produces counts for the six categories of dependents (0 through 5) by using a series of decisions. Figure below shows the flowchart for the decisionmaking part of such an application. In the flowchart, the variable dep is compared to 0. If it is 0, 1 is added to count0. If it is not 0, then dep is compared to 1. Based on the result, 1 is added to count1 or dep is compared to 2, and so on. Each time the application executes this decision-making process, 1 ultimately is added to one of the six variables that acts as a counter. The dependent-counting logic works, but even with only six categories of dependents, the decision-making process is unwieldy. What if the number of dependents might be any value from 0 to 10, or 0 to 20? The basic logic of the program would remain the same; however, you would need to declare many additional variables to hold the counts, and you would need many additional decisions.Although this logic works, its length and complexity are unnecessary once you understand how to use an array.Using an array provides an alternate approach to this programming problem and greatly reduces the number of statements you need. When you declare an array, you provide a group name for a number of associated variables in memory. For example, the six dependent count accumulators can be redefined as a single array named counts. The individual elements become counts[1], counts[2], counts[3], counts[4], counts[5], and counts[6].The true benefit of using an array lies in your ability to use a variable as an index to the array, instead of using a literal constant such as 0 or 5. Within each decision, the value compared to dep and the constant that is the index in the resulting Yes process are always related. That is, when dep is 0, the index used to add 1 to the counts array is 1; when dep is 1, the index used for the counts array is 2, and so on. Therefore, you can just use dep as an index to the array. You can rewrite the decisionmaking process as simply: counts(dep+1) = counts(dep+1) + 1 ;Note that, for loop can also count backwards. For example: a = [ 1,2,3,4,5] ; for i=5:-1:1 disp([ 'a(' num2str(i) ') = ' num2str(a(i)) ]) ; endThe output will be; a(5) = 5 a(4) = 4 a(3) = 3 a(2) = 2 a(1) = 1Operations on Arrays and VectorsOperating on arrays involves two aspects: Operating on two or more arrays Element-wise operations All arithmetic operators, such as +, -, *, /, %, ^, etc., can be used in both cases.When you need to do element-wise operations, then a dot . is placed before the operator. The element-wise operators therefore become .+, .-, .*, ./, .%, and .^. For example, we write 2.+a to add 2 to each element individually. This can be done regardless of size and is implemented uniformly on all the elements of the matrix or vector. This will become clearer in the following example. >> a = [1,2;3,4] a = 1 2 3 4 >> b = [5,6;7,8] b = 5 6 7 8 >> a + b ans = 6 8 10 12 >> 2 .+ a ans = 3 4 5 6 >> -10 .+ b ans = -5 -4 -3 -2Other mathematical functions— like sin(), cos(), asin(), etc.—are already vectorized, which means they perform the operation on each element of the given array. When a and b are matrices to be added/subtracted, their elements are added/subtracted with elements in the same position. For this reason, the size of the two matrices added or subtracted must be the same. There are many operations that can be performed on a matrix or any array. For example: >> a = rand(2,3) a = 0.6787 0.7431 0.6555 0.7577 0.3922 0.1712 >> b = rand(2,3) b = 0.7060 0.2769 0.0971 0.0318 0.0462 0.8235 >> c = (a < b) c = 1 0 0 0 0 1 Here, two random matrices are created using random number generator function rand(x,y).Then, these two matrices are compared to each other element-wise. The matrix c has elements, either 1 or 0, which are assigned by determining whether the corresponding elements of a are smaller than b. The matrix c contains logical data types, i.e., 1 and 0 represent the Boolean quantities True and False.A square matrix has an equal number of rows in each dimension. The built-in function issquare() can be used to check if the given matrix (represented by an array) is a square matrix and whether an appropriate function should be used. The result is 1 if the matrix is a square matrix and 0 otherwise. Its usage is illustrated in the following code: >> a = [1,2;2,3]; >> issquare(a) ans = 1 >> b = [1,2;2,3;3,4]; >> issquare(b) ans = 0Read about rank(), trace(), norm(), eye() functions in the documentation. You can automatically generate an array by defining a rule using the colon : operator or by using the linspace() arguments. These methods are widely used, as they are convenient ways to generate large matrices. It is important to remember that you can suppress the output being printed on the terminal by ending the command with the semicolon ; operator, since it can be quite annoying to see a large set of numbers on the terminal.You can generate a series of numbers and store them as arrays by using the command start:step:stop, where the numbers representing start, step, and stop are real numbers. The result is an array. Defining the brackets ([]) is optional. If the step is not defined, then it is taken as 1. >> x = 1:2:10 % without brackets, start=1, step=2, stop=10 x = 1 3 5 7 9 >> x = [1:1:10] % with brackets, start=1, step=1, stop =10 x = 1 2 3 4 5 6 7 8 9 10 >> y = 2.2:3.8 % start=2.2, stop=3.8, step=1 y = 2.2000 3.2000 >> y = 2.2:0.2:3.8 % start=2.2, step=0.2, stop=3.8 y = 2.2000 2.4000 2.6000 2.8000 3.0000 3.2000 3.4000 3.6000 3.8000The linspace(start,stop,n) command produces an array starting with the first number and stopping at the second one, with a total of n numbers. Hence, they are linearly spaced. >> a = linspace(1,2,5) % start=1, stop=2, number of items=5 a = 1.0000 1.2500 1.5000 1.7500 2.0000 >> a = linspace(1,2,10) % start=1, stop=2, number of items=10 a = 1.0000 1.1111 1.2222 1.3333 1.4444 1.5556 1.6667 1.7778 1.8889 2.0000A matrix that contains all 1s or all 0s is a ones matrix and zeros matrix, respectively. These are generally used for initialization of matrices of desired dimensions. The initialized matrix is then used for manipulations. These matrices can be created as follows: >> ones(3,3) ans = 1 1 1 1 1 1 1 1 1 >> zeros(3,3) ans = 0 0 0 0 0 0 0 0 0Matrix MultiplicationMatrix multiplication and division are not straightforward tasks. An m×n matrix can only be multiplied by a n×t matrix, which results in m×t matrix. This is performed by multiplying elements of rows with elements of columns to get new elements.Note that, for matrices a and c, a*c performs matrix multiplication, a.*c performs elementwise multiplication. The requirements are as follows:For matrix multiplication, the inner dimensions must match.For element-wise multiplication, all dimensions must match.When the inverse of a matrix is multiplied by itself, you get an identity matrix, i.e., a matrix with 1 as its elements in the diagonal direction and 0 everywhere else. This can be used to determine if the functions inv() and pinv() are working fine. >> a = [2,-2;4,2] a = 2 -2 4 2 >> inv(a) ans = 0.16667 0.16667 -0.33333 0.16667 >> a*inv(a) ans = 1.00000 0.00000 0.00000 1.00000Double- and Triple-Nested Loops for 2D and 3D ArraysWe will implement matrix addition without the support of matrix addition capabilities of Octave. Matrix addition is formulated as follows for any two m×n matrices A and B:cij=aij+bij 1≤i≤m, 1≤j≤n 1Therefore, the implementation requires two nested for-loops: for i = 1:m for j = 1:n C(i,j) = A(i,j) + B(i,j) ; end endThere are many ways for flowcharting these two nested for-loops: For nested for-loops, we will prefer to use the following notation. Note that this version is more compact and has a one-to-one correspondance with loop statements in most programming languages. Matrix multiplication is formulated as follows for two matrices A and B:cij=k=1maikbkj 1≤i≤n, 1≤j≤p for An×m, Bm×p, Cn×p 1Therefore, the implementation requires three nested for-loops: for i = 1:n for j = 1:p sum = 0 ; for k = 1:m sum = sum + A(i,k) + B(k,j) ; end C(i,j) = sum ; end endStrictly speaking, the variable sum is not really necessary. However we use it to the proper place for instructions that must be executed between the iterations of nested loops.Flowchart the matrix multiplication algorithm.Some Self-Study ExcersisesQuestion 1For Gaziantep, monthly rainfall data for 5 years (in Kg/m2) is provided in a table such as below (Not all numbers are shown):JanFebMarchAprilMayJuneJulyAugSept OctNovDec1985101520121075271011141986819871219889198911Assume that these values are given in a 5×12 matrix called rain. From this matrix, calculate the average rainfall for each month and write them into an 1×12 array called avg. (For the above table, the first element of avg should have the value of 10 ( avg(1) = 10 since 10+8+12+9+11/5 = 50/5 = 10 ).Solution:The flowchart:avg(j) = sum / 5.0Create and populate matrix rain;Create 1x12 vector avg;endsum=0j=1:12i=1:5sum = sum + rain(i,j)The Octave code is as follows. Be careful about the order of the indices of the matrix rain. rain = randi(50,5,12); % Create a rainfall matrix with random entries avg = zeros(1,12); for j = 1:12 sum = 0 ; for i = 1:5 sum = sum + rain(i,j) ; end avg (j) = sum / 5.0; endQuestion 2Find the greatest number in any array of numbers.Question 3Multiply negative numbers in an array of numbers with 10.Question 4Copy an ordered array of numbers in reverse order into another array.Question 5Sort the numbers in an array in ascending (increasing) order.Question 6Sort the numbers in an array in descending (decreasing) order.Question 7Select the positive numbers from an array of numbers and place them into a new array in descending order.Question 8Insert a number into an array of numbers in ascending order, so that the order is not disturbed.Programming EMV (Expected Monetary Value)The expected monetary value, or EMV, for any decision is a weighted average of the possible payoffs for this decision, weighted by the probabilities of the outcomes. Using the EMV criterion, you choose the decision with the largest EMV. It is important to understand what the EMV of a decision represents—and what it doesn’t represent. Assume that the payoff table indicates that the result from decision D will be a loss of $30 with 0.5 probability, a gain of $30 with 0.2 probability, or a gain of $80 with 0.3 probability. Thus, the calculated EMV of 15 for decision D (?30(0.5) + 30(0.2) + 80(0.3) = 15) does not mean that you expect to gain $15 from this decision; it will never be a gain of $15. The EMV is only a weighted average of the possible payoffs and it can be interpreted as follows: Imagine that this situation can occur many times, not just once. If decision D is used each time, then on average, you will make a gain of about $15. About 50% of the time you will lose $30, about 20% of the time you will gain $30, and about 30% of the time you will gain $80. These averages to $15. For this reason, using the EMV criterion is sometimes referred to as “playing the averages.” Consider the following example:A Ski Resort is planning the ski lift operation for its new ski resort. Management is trying to determine whether one or two lifts will be necessary; Each lift can accommodate 250 people per day. Skiing normally occurs in the 14-week period from December to April, during which the lift will operate seven days per week (i.e., 98 days)The projection of the impact of the economic conditions on revenue are stated as follows: The first lift will operate at 90 percent capacity if economic conditions are bad, the probability of which is believed to be about a 0.3. During normal times the first lift will be utilized at 100 percent capacity, and the excess crowd will provide 50 percent utilization of the second lift. The probability of normal times is 0.5. Finally, if times are really good, the probability of which is 0.2, the utilization of the second lift will increase to 90 percent. The equivalent annual cost of installing a new lift, recognizing the time value of money and the lift’s economic life, is $50,000. The annual cost of installing two lifts is only $90,000 if both are purchased at the same time. If used at all, each lift costs $200,000 to operate, no matter how low or high its utilization rate. Lift tickets cost $20 per customer per day. Should the resort purchase one lift or two? The decision tree, where the payoff (in $000) for each alternative-event branch is shown below. $256.0 One LiftNormal p=0.5Bad p=0.3 $191=0.9490-(50+200) $240=1.0490-(50+200) $240=1.0490-(50+200)Good p=0.2$225.3Two LiftsNormal p=0.5Bad p=0.3 $151=0.9490-(90+200) $245=1.5490-(90+400) $441=1.9490-(90+400)Good p=0.2$256.0The total revenues from one lift operating at 100 percent capacity are $490,000 (or 250 customers × 98 days × $20/customer-day).Calculate the EMV of one and two lift cases using only a single command for each case. Solution: oneLiftEMV = sum( ( ([0.9, 1, 1] .* 490) .- 250 ) .* [0.3, 0.5, 0.2] ) ; twoLiftsEMV = sum( ( ([0.9, 1.5, 1.9] .* 490) .- [290, 490, 490] ) .* [0.3, 0.5 ,0.2] );Solving a Set of Linear EquationsAssume that you have the following: You want to find those values of x, y, and z for which all three equations hold true. To do this, the first matrix formed from these equations can be written as, AX=B where X=A-1B: The solution is given by X=A1B which involves a matrix inversion. You find the inverse of A and then multiply the resultant matrix with the matrix given by B to find a solution. This can be achieved using the inv() function if the input matrix is a square matrix. Alternatively, you can accomplish this task in just one command, using the left matrix divide operator (backslash, \) as A\B. >> A = [1,-4,1; -1,-1,1; 1,1,-1] ; >> B = [4; -1; 2]; >> A\B 1.60526 0.76316 -0.65789For ordinary numbers, xb=a is the same as bx=a. But since matrix multiplication is not commutative, there are two different possible generalizations of "division" to matrices. If B is invertible, then you can form AB?1 or B?1A, but these are not in general the same matrix. They are the solutions to XB=A and BX=A respectively. If B is not invertible, then XB=A and BX=A may have solutions, but the solutions will not be unique. In case when inverse doesn't exist so called pseudoinverse may be used.Read about the pinv() function in the documentation. PLOTTINGThe ability to provide quality visualizations from output data is a key part of data analytics. Octave provides this functionality too. Its plotting features include choosing from various types of plots in 2D and 3D formats, decorating plots with additional information such as titles, labeled axes, grids, and labels for data, and writing equations and other important information about data. 2D PlottingThe plot(x,y) FunctionSince you need to plot data on two axes, you first need to create them. Let’s assume that the x axis has 100 linearly-spaced data points, whereby y = x2.First you define a variable x and place 100 equally-spaced data points from 0 to 100. This creates a 1×100 matrix. Using the scalar operation of exponentiation, you define the variable y as the x2. Then you use the function plot(), which takes two arguments as the x-axis and y-axis data points. >> x = linspace(0,100,100); >> y = x .? 2 ; >> plot(x,y) Typing help plot on the command prompt gives you useful insight into this function used to plot two-dimensional data. The area(x,y) FunctionThe area() function results in a similar plot as the plot() function, but it also shades the area under the curve, as shown above. The bar(), barh(), and hist() FunctionsBar charts are primitive but very effective in visualizing primary statistical information. There are three ways to plot bar charts and histograms: bar() plots a vertical bar chart barh() plots a horizontal bar chart hist() plots a histogram chart. x = [1, 2, 3, 4, 5, 6] ; y = [0.5, 2.2, 0.7, 1.5, 2.5, 0.9] ; bar(x,y) barh(x,y) Plotting Multiple Plots on the Same GraphMultiple plots can be plotted on the same graph by simply supplying x and y axes vectors, as shown below: clear all; clf; x = linspace(1,100,100); y1 = x .^ 2.0; y2 = x .^ 2.1; y3 = x .^ 2.2; y4 = x .^ 2.3; plot(x,y1, 'Marker','*', 'MarkerFaceColor','red', x,y2, 'Marker','+', 'MarkerFaceColor','blue', x,y3, 'Marker','x', 'MarkerFaceColor','green', x,y4, 'Marker','s', 'MarkerFaceColor','cyan') grid on legend('x^2','x^{2.1}','x^{2.2}','x^{2.3}'); xlabel('x-axis') ylabel('y-axis') title('Multiple Graphs')Plotting Multiple Plots SeparatelyThe subplot(row,column,index) command is used to plot multiple plots within the same figure separately. subplot(2,2,4) means that the plot will be on the second row, in the second column, and in the fourth index. clear all; clf; x = linspace(1,100,100); y1 = x.^2.0; y2 = log(x); y3 = sin(x); y4 = log10(x); subplot(2,2,1), plot(x,y1) xlabel('x-axis'), ylabel('x^2') title('Multiple Graphs 1: y=x^2') subplot(2,2,2), plot(x,y2) xlabel('x-axis'), ylabel('log(x)') title('Multiple Graphs 2: y=log(x)') subplot(2,2,3), plot(x,y3) xlabel('x-axis'), ylabel('sin(x)') title('Multiple Graphs 3: y=sin(x)') subplot(2,2,4), plot(x,y4) xlabel('x-axis'), ylabel('log10(x)') title('Multiple Graphs 4: y=log10(x)')The pie() FunctionYou can create a pie chart using the pie() function. This provides a very powerful tool to visualize the parts of a whole. The pie chart can be made by first defining the parts as an array. Then if pie() function is fed directly, you’ll get a color-coded pie chart showing the percentages of each part. When a show() array is also used, it explodes only those parts whose corresponding element is 1. x = [3,2,1,4,1,2]; subplot(1,2,1) pie(x) subplot(1,2,2) show = [0,1,0,1,0,1]; pie(x,show)The stem() FunctionStem() plots draw data points as stems that extend from equally spaced values. The code that plots y = sin(x) for (-4π, 4π) is shown here. x = -4*pi:4*pi; y = sin(x); stem(y)3D PlottingThe plot3() FunctionA three-dimensional line plot can be created with the plot3() function. This function is exactly like the two-dimensional plot function, except that each point is represented by x, y, and z values instead of just x and y values. The simplest form of this function is plot(x,y,z); where x, y, and z are equal-sized arrays containing the locations of data points to plot. As an example of a three-dimensional line plot, consider the following functions x(t) = e-0.2t cos 2ty(t) = e-0.2tsin 2tThese functions might represent the decaying oscillations of a mechanical system in two dimensions, so x and y together represent the location of the system at any given time. Note that x and y are both functions of the same independent variable t.The code: t = 0:0.1:10; x = exp(-0.2*t) .* cos(2*t); y = exp(-0.2*t) .* sin(2*t); plot3(x,y,t); title('\bfThree-Dimensional Line Plot'); xlabel('\bfx'); ylabel('\bfy'); zlabel('\bftime'); grid on;The graph:End of Lecture Notes. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download