1 / 56

Computer Programming with MatLab First Bytes Summer Camp

Computer Programming with MatLab First Bytes Summer Camp. Mary Eberlein and Mike Scott. Who am I? . From St. Charles, Missouri Attended Stanford University 1986 - 1990 US Navy 1990 - 1998, Nuclear Submariner Married 1997 to Kelly, A US Navy Nurse

gazelle
Download Presentation

Computer Programming with MatLab First Bytes Summer Camp

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Computer Programming with MatLabFirst Bytes Summer Camp Mary Eberlein and Mike Scott Using MatLab

  2. Who am I? • From St. Charles, Missouri • Attended Stanford University 1986 - 1990 • US Navy 1990 - 1998, Nuclear Submariner • Married 1997 to Kelly, A US Navy Nurse • Masters in CS, 1998, Rensselaer Polytechnic Institute • Out of Navy 1998, moved to Austin to work for Motorola (Worst 10 weeks of my life) • 2 years teaching CS at Round Rock High School • 3 years as a lecturer here at UTCS department Using MatLab

  3. Using MatLab

  4. Agenda • Learn what computer programming is • Learn how to do programming with another program called MatLab • Programming concepts • mathematical expressions • variables, boxes that hold numbers • assignment, giving variables new values • matrices and arrays, larger more useful variables • functions, solving problems with mathematical expressions, variables, and assignments • Loops, do things over and over • Strings, another kind of variable • Decision making, doing things only if certain things are true Using MatLab

  5. What is Computer Programming? • "Having surveyed the relationships of computer science with other disciplines, it remains to answer the basic questions: What is the central core of the subject? What is it that distinguishes it from the separate subjects with which it is related? What is the linking thread which gathers these disparate branches into a single discipline? My answer to these questions is simple -- it is the art of programming a computer. It is the art of designing efficient and elegant methods of getting a computer to solve problems, theoretical or practical, small or large, simple or complex. It is the art of translating this design into an effective and accurate computer program." • C.A.R. Hoare, Essays in Computing Science • Many different areas of Computer Science, computer programming is an important tool in almost all of those areas Using MatLab

  6. Algorithms and Computer Programs • Algorithm, a set of detailed, exact instructions, to carry out some task or solve some problem • Consider the following problem, • create an algorithm to look up the phone number for Papa John's Pizza in the yellow pages • A computer program is the expression of an algorithm in a language a computer can understand • MatLab is a computer programming language Using MatLab

  7. Starting MatLab • Click the start button in the lower left • select the programs folder • select the MatLab folder • select MatLab (It takes a while to start up.) • MatLab starts • a window with three areas • Command Window • Command History • Workspace Browser • Maximize the window Using MatLab

  8. Click this icon to maximize WorkspaceBrowser Command Window CommandHistory Using MatLab

  9. Simple MatLab Actions • Put the cursor in the Command Window and click next to the prompt. The prompt is the set of double greater than symbols >> • type in 2 + 2 and press the Enter or Return key • What happened? Using MatLab

  10. More Simple Actions • Try these commands one at a time 2 + 10 2 - 10 2 * 3 1.5 * 3 10 / 3 2 ^ 3 2 8 3 • What happened? • Trying pressing the up arrow once. • Try several times. Using MatLab

  11. Is This Computer Programming? • So what is the difference between MatLab and a calculator? • At this point not much • You will write more complicated and involved calculations, but at its very heart a computer is a lot like a four function calculator • The Big Difference is a computer can do calculations really fast • Pentium 4 chip from 2001 can perform approximately 1,700,000,000 computations per second • If something can be represented numerically it can be stored on a computer and manipulated via the computer!pictures, images, video, music, text, DNA data, … Using MatLab

  12. More MatLab • Like a calculator and algebra MatLab has functions • try this command >> sqrt(16) • What happened? What does sqrt do? • MatLab has hundreds of built in functions • We will use only a few • We will also create our own functions • This is computer programming!!! Using MatLab

  13. Variables • Try the following command >> firstvar = 12 • what happened? Look in the Workspace Browser section. Using MatLab

  14. Variables • There is now an entry in the Workspace Browser for firstvar and an icon for it • Try the command >> firstvar • What happened? • Double click on the icon for firstvar in the Workspace Browser Using MatLab

  15. Variables • A variable is a storage container • The variable has a name, a type, and a current value • The name of our this variable is firstvar • The type of our firstvar is double array • The current value of firstvar is 12 • The name of a variable cannot be changed • Some languages allow the data type to be changed, some do not. MatLab allows you to change the type • The current value of a variable can be changed • another fundamental concept of programming • MatLab lets you look at the contents of a variable • the window that opens when double clicking on the firstvar icon Using MatLab

  16. Array Editor Window Nameof Variable Current Valueof Variable Leave the Array Editor Window for firstvar open and back inthe Command Window try the following command >> firstvar = 20 What happened? Using MatLab

  17. Manipulating Variables • Try the following command >> firstvar = firstvar + 1 • This is not a mathematical statement. It is a command! • if it were a mathematical statement it would be false • in many programming languages including MatLab the equals symbol, = , means perform an assignment • definition of assignment: evaluate the expression on the right hand side of the equals sign and store the answer in the variable on the left hand side of the equal sign Using MatLab

  18. Experiment with Assignment • Some of these commands purposefully have errors >> firstvar = 2 >> firstvar = firstvar + 2 >> firstvar = firstvar * 2 >> firstvar = firstvar * 2 + 2 >> firstvar = firstvar + 2 * 2 >> firstvar = (firstvar + 2) * 2 >> firstvar + 2 = firstvar >> firstvar = firstVAR + 2 Using MatLab

  19. More Variable Assignment >> firstvar = 10 >> firstvar = firstvar - 100 >> secondvar = abs(firstvar) >> thirdvar = firstvar * secondvar • Some thing to notice • firstvar and firstVAR are not the same thing, they are two different, unique names • the left hand side must be a single variable • when a variable that has not been used yet is placed on the left hand side the variable is created and can be seen in the Workspace Browser Using MatLab

  20. Matrices - A More Complex Variable • MatLab is designed to work with mathematical matrices • A mathematical matrix is a collection of numbers in a rectangular arrangement 2 13 5 15 1 6 • Properties of the matrix include the number of rows and columns • A cell is specified by its row and column number cell(1, 1) = 2 cell(1, 2) = 15 cell(2, 3) = ? Using MatLab

  21. Creating Matrices in MatLab • In MatLab a variable can hold an entire matrix. Try the following command >> matvar = [2 13 5; 15 1 6] • [ and ] are called the square brackets • double click on the mat icon in the Workspace Browser and examine the contents of the variable matvar Using MatLab

  22. Cells in a Matrix • Each individual cell or element is a variable • Try the following command >>firstvar = matvar(1,2) + matvar(2,1) >> matvar(2,2) = 3 * matvar(2,3) • What is the value of firstvar now? • to refer to a particular cell of a matrix variable we use subscripts • matvar(1,2) refers to the cell at row 1, column 2 • matvar(2,1) refers to the cell at row 2, column 1 • matvar refers to the entire matrix Using MatLab

  23. Arrays - A Special Kind of Matrix • A matrix with a single row is called an Array or Vector • There are many ways to create arrays (and matrices) in MatLab >> arrayvar1 = [1 4 9 16 25] >> arrayvar2 = 1:10 >> arrayvar3 = 5:5:100 >> arrayvar4 = zeros(1,10) >> arrayvar5 = ones(1,15) Using MatLab

  24. Loading Data from a File • Typing in all this data can be a pain. • Sometimes it is easier and more convenient to read data from a file • Getting this done correctly can be a pain, but realize it is not the essence of computer programming. (The file sampleList.dat must be in the workspace directory.) c:\MatLab\Work >> load sampleList.dat >> sampleList Using MatLab

  25. Referring to a Single Array Element • MatLab treats matrices with a single row (arrays) in a special way • An element may be referenced without specifying the row. • Try the following command >> arrayvar1 = [2 3 5 7 11 13] >> firstvar = list1(2) + list1(3) • What is the value of firstvar now? • Care must be taken when accessing elements of an array. • Try the following command: >> firstvar = arrayvar1(4) + arrayvar1(10) Using MatLab

  26. Basic Operators and Functions • MatLab basic mathematical operators + (addition) - (subtraction) * (multiplication) / (division) ^ (power) () (specify evaluation order) • In addition to these basics MatLab has hundreds of functions.Not a symbol, but a named function Using MatLab

  27. A Few MatLab Functions • Format is functionName(inputInfoList) inputInfoList is zero or more values separated by commas. These can be values or variables • Try these function calls >> abs(-101) >> round(1.234) >> isprime(13) >> isprime(111) >> factor(13) >> factor(111) >> list1 = factor(792) >> max(3, 5) >> max(firstvar, secondvar) >> max(list1) Using MatLab

  28. Function Facts • A function has inputs • 0 or more values. • the values can be variables • may have different numbers of input • A function has an output • a single value, array, or matrix • result can be assigned to a variable • You can (and will) create functions to do various tasks • stored in a separate file, in MatLab these are called M-files Using MatLab

  29. Creating a Function • Create a function that determines the area of a triangle • to create a new M-File click the new M-File icon in MatLab • This opens the M-File editor • Type the first line. Need name for function, name for output, and list of inputs • skip 1 line • write command(s) • save and test in command space Using MatLab

  30. Sample Function Using MatLab

  31. Details of Function name of the function variable tohold outputof function inputs tofunction function c = hyp(a,b) % calculates length of the % hypotenuse of a right % triangle. (These are comments) c = a * a + b * b; c = sqrt(c) the wordfunction lets MatLabknow this is a function commands.these are carried out every time function is carried out. This function calls another! optional semicolon at end of command: suppresses output of command Using MatLab

  32. Array Outputs from Functions function result = cubedata(lengthOfSide) result = zeros(1,3) result(1) = 12 * lengthOfSide result(2) = 6 * (lengthOfSide ^ 2) result(3) = lengthOfSide ^ 3 lengthOfSide Using MatLab

  33. Another Function • Consider a rectangular three dimensional object Write a function whose output is an array with three elements 1. sum of the length of the sides of the object 2. surface area of the object 3. volume of the object Using MatLab

  34. Steps to Writing a Function • What must the function do • what are the required inputs? • what is the desired output? • how do I get the desired output based on the required input? • Notice, the area of expertise here is geometry and programming • One of the joys of being a computer scientist is that computer science is applicable to so many different areas Using MatLab

  35. Steps to Writing a Function in MatLab • Once clear on what must be done • pick name for function • pick name for output (result) • pick names for inputs • complete commands for function • save function • test function in command window Using MatLab

  36. Harnessing the Power • Why use a computer? • to manipulate data that can be stored in a numeric format when you need to do a lot of manipulating • the computer is fast! • Function for computing properties of a rectangular solid • were we taxing the resources of the computer? • the power of a computer is its speed. It can do a lot of simple things very quickly Using MatLab

  37. Loops • say I want a function that creates an array that holds the squares of the first 10 positive integers in order. • lots of different ways to do this • one simple way squares = [1 4 9 16 25 36 49 64 91 100] • seems simple • what if I want the function to create an array that holds the squares of the first N positive integers in order? • N is a variable! Using MatLab

  38. First Attempt function result = squares(N) result = zeros(1,N) result(1) = 1 result(2) = 4 result(3) = 9 … • what's the problem? Using MatLab

  39. Loops are for Repetition • A loop is a way to repeat a command a variable number of times • more syntax -> gain powerful tool function header create array ofcorrect size function result = squares(N) result = zeros(1,N) for num = 1:N result(num) = num * num end for loop Using MatLab

  40. Anatomy of a for Loop • a for loop starts out with the word for • this similar to the word function. It has a special meaning in MatLab, in this case as a signal this is the start of a for loop (reserved words or keywords) • next comes a variable • in the previous example this is num. This is called the loop control variable. It determines how many times the commands of the loop will be executed • The next part of the loop assigns the loop control variable an initial value, in this case 1 • the :N indicates what value the loop control variable, num, will go up to • so num will start at 1 and go up by 1 until it reaches N Using MatLab

  41. Inside the for loop • after the first line of the for loop is the body of the for loop • this is a series of commands • any commands you like • these are executed in order until the end statement is reached • end is another special word (reserved word or keyword) • tells MatLab this is the end of the for loop Using MatLab

  42. So What Happens? result = zeros(1,N) for num = 1:N result(num) = num * num end num starts at 1 result(1) is set to 1 * 1 num goes up by 1 to 2 result(2) is set to 2 * 2 num goes up by 1 to 3 result(3) is set to 3 * 3 and so on and so on… Using MatLab

  43. Figuring out Square Roots • Let's work with determining square roots • Newton's method for approximating square roots adapted from the Dr. Math websiteThe goal is to find the square root of a number. Let's call it num1. Choose a rough approximation of the square root of num, call it approx. How to choose?2. Divide num by approx and then average the quotient with approx, in other words we want to evaluate the expression ((num/approx)+approx)/2 3. How close are we? In programming we would store the result of the expression back into the variable approx.4. How do you know if you have the right answer? Using MatLab

  44. Doing it the Hard Way • Use variables, expressions, and assignment commands in the command window to determine the square root of 123456 start approx at 0.01 To speed this up we could write a function that determines square roots using the same technique Using MatLab

  45. Write your Own Square Root Function • don't call your function sqrt, pick some other name • you only need a 1 x 1 matrix so you should haveresult = zeros(1,1) • Use a for loops to carry out 10 steps of the approximation • compare the answer from your function to the result from the sqrt function in MatLab for the numbers 5 10 1178 108271 2137810 Using MatLab

  46. Strings, Another Kind of Data • So far we have been working with numbers • Computers are also very useful for dealing with text • letters and characters • Most programming environments, including MatLab, have a way of representing information consisting of text • In MatLab this is via Strings • a collection of zero or more characters (not numbers) • to indicate a String a pair of single quotes is used • the characters of the String are between the single quotes Using MatLab

  47. Test this Code string1 = 'First Bytes' string1(1) string1(3) string1(7) What is the index of the e? string1(8) = i nums = double(string1) Using MatLab

  48. Encoding - Using Numbers to Represent Something Else • The output of the last command on the previous page is especially interesting • any ideas on what it means? • Try this command string1 = 'ABCDEFGHIJ' nums = double(string1) Hmmmm Using MatLab

  49. Encoding Text • A computer stores numbers • Those numbers can be made to represent many, many things for example characters • An encoding scheme is a way to match up numbers to the other information we want the number to represent • For text, letters, characters there are many encoding schemes • The most popular are ASCII, the America Standard Code for Information Interchange and Unicode Using MatLab

  50. A bit of the ASCII Encoding Scheme The computer needs a number, we are comfortable with text. Sometimes we have to switch back and forth. Try the following commands: >> nums = 1:128>> string1 = char(nums) Using MatLab

More Related