1 / 49

Introduction to Programming using Matlab

Introduction to Programming using Matlab. P Duffour Jan 2008. WARNINGS!. This introduction assumes you know nothing about programming or Matlab! It has two objectives: Sketching out what programming is in general Teaching you the basics of Matlab.

lydie
Download Presentation

Introduction to Programming using Matlab

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. Introduction to Programmingusing Matlab P Duffour Jan 2008

  2. WARNINGS! • This introduction assumes you know nothing about programming or Matlab! • It has two objectives: • Sketching out what programming is in general • Teaching you the basics of Matlab

  3. A brief outline of computer architecture: • For our purpose it is important to know a few basic things about how computer works. The essential elements are: • The Processor (or CPU = computer processing unit). This is the core that processes data and executes tasks. • RAM = non permanent memory. This is like a temporary dumping space which the CPU uses to store things while it’s working. The RAM content gets wiped out when the computer is turned off. • Storage devices (hard drive, USB sticks, CD-ROM etc) are used to store or memorise data ‘permanently’. ►In a kitchen the RAM would be the worktop which you clean after cooking and the storage devices are the cupboards where stuff is stored away to be used again later. • Input/Output devices (Keyboard, Screen, mouse etc) are necessary for humans to interact with the computer. Mice and keyboards are input devices. Screens and loudspeakers are output devices. Storage devices are also Input/Output devices but of a particular kind.

  4. What is programming? Breaking down a complex task into simpler ones that a computer can deal with • Computers work fast but they are really quite stupid in that they can only do very basic tasks at a time so the programmer has to do lots of ‘breaking down’.• Computers also work in a very logical way which is quitedifferent from the normal fuzzy functioning of the human brain. So the breaking down has to be done in a logical and systematic way• The breakdown in elementary tasks must be sequential: tasks are must be carried out a linear order from first to last■ Now try Task 1

  5. What is a programming language? • A set of keywords (lexicon) = a set of pre-defined words that can be combined into statements that a computer can understand and execute • A syntax or grammar = ways of writing statements for them to be understood Statements = orders for the computer to execute ► Deep down, computers only understand 0s and 1s. (high level) Programming languages provide users with a set of words which correspond to an intermediate level of complexity between the 0 and 1 level and the complex tasks that a user may want the computer to do. Statements are basic but fundamental tasks that can be executed by the computer but that human beings can still relate to. ► Here are two examples of statements: One in the language C++ cout << “hello”; Equivalent statement in Matlab disp(`hello`); When executed, these statements or commands both result in the word hello to be displayed on the screen. • cout and disp are keywords of their respective language • Compare the different syntaxes: cout needs << and “, disp needs ( and `

  6. What is a program? • A sequence of statements or ‘commands’ written in a programming language such that when the sequence is executed the computer does a specific task. • Next is an example of program. This program takes as input a number of seconds and converts it into a hour/minute/second format. • To give you an example of another programming language, the same program is given in C++ and Matlab

  7. #include <iostream.h> main() { // Convert a number of seconds to the 'hours, //minutes, seconds' format int total; cout << "Time in seconds ?\n"; cin >> total; //Read in time int hour = total/3600; int minute = (total-3600*hour)/60; int second = total-3600*hour - 60*minute; cout << "A time of " << total << "seconds\n"; cout << "corresponds to "; cout << hour << " Hours\n"; cout << minute << "Minutes and \n"; cout << second << "Seconds \n"; return 0; } % Convert a number of seconds to the % 'hours, minutes, seconds' format total = input("Time in seconds ?\n“); %Read in time hour = total/3600; minute = (total-3600*hour)/60; second = total-3600*hour - 60*minute; disp(sprintf(`A time of %g seconds\n’,total); disp(`corresponds to `); disp(sprintf(`%g Hours\n`,hour); disp(sprintf(`%g Minutes\n`,minute); disp(sprintf(`%g Seconds\n`,second); Example of the same program in two different languages: C++ Matlab ■ Now try Task 2

  8. Source Code - Execution A computer program can mean two things: • The list of instructions as shown on the previous slide. This is usually called the (source) code. It is essentially a text file. It does nothing in itself. • An ‘executable file’ which actually does what the program is intended to do. • To go from code to execution, one needs an extra stage of translation. This translation transforms the list of instructions you write into 0s and 1s that the computer understand (called machine code).

  9. Compilation and Scripting • You don’t need to do this translation yourself. You just have to run your code through a special program that does it for you. • Programming languages can be split into two distinct categories depending on how they do this translation from code to execution. • Some are ‘compiled’ languages. They use a compiler to translate the code. • Some are scripting languages. They translate sequentially one statement at a time using a command interpreter.

  10. Compilation Source Code Executable file (text file myprogram.cppcontaining the instructions) (something like myprogram.exe which runs on a computer) Compiling languages Compiling languages work like this: ►Most professional programming languages are of this type because the executable file runs faster and once compiled you don’t need to worry about either source code or compilation. You can just get on using your .exe file. ► C++ is a compiled language. ► Mainstream commercial programs are given as executables. As end users you never see the source code of MS Word for instance. All you get is Word.exe – the code is a Microsoft trade secret. ■ Now try task 3

  11. Scripting languages • Scripting languages execute a program line by line and do not produce a separate executable file. This makes it easier for you to check part of your code. • With a scripting language, you need the source code and the command interpreter to execute the program. • Matlab is a scripting language. JavaScript is another one. • Scripting/Compiling make no difference as far as writing the code is concerned. You still need to break down the complex problem into elementary tasks.

  12. The programming process Programming is an iterative process. The syntax rules of programming languages are very precise, so it is very easy to make mistakes. The process of correcting mistakes is called debugging. Writing Code Executing (see what the code does) Debugging This goes on until the program does what it is supposed to be doing.

  13. Syntax errors/programming errors • As long as you have syntax errors in your code, it simply won’t execute but you will be prompted by the compiler/command interpreter where it thinks the error is. For instance disp[“hello”] will produce a syntax error when interpreted in Matlab. • Programming errors can be more tricky to spot. You program can ‘run’ or execute but it doesn’t do what it’s supposed to be doing. This would be the case if you had written second = total+3600*hour + 60*minute; instead of second = total-3600*hour - 60*minute;

  14. What is Matlab? A programming (scripting) language designed to be very easy for: • Computations with vectors, matrices, etc… • Standard but non-trivial mathematical operations (e.g. polynomial root finding, matrix eigenvalue extraction…) • Plotting and customise plots ►It is not the kind of programming language used by professional software engineers but it is good to learn programming

  15. Now start Matlab…. • In WTS go to Start →Programs → Unix applications → Matlab • Wait until a large complicated window appears

  16. The Matlab Programming Environment When you start Matlab, a window is launched: this is the Matlab Programming Environment. In its default configuration, this window is made of four frames called: • Workspace • Current Directory • Command History • Command Window The Command Window is the most important one. It is the command interpreter. The other windows are just there to assist you in programming and debugging.

  17. Command Line Window To get started, select "MATLAB Help" from the Help menu. >> The >> is called a prompt. This is where Matlab waits for instructions. It is like an ear constantly waiting for orders to be executed. Entering an instruction means typing it at the command line prompt and pressing return. For the time being you will be entering instructions at the prompt and not write a program as such.

  18. How the Command Window work? This ‘ear’ somehow relates to three entities in the computer: • It is linked to some specific memory space allocated to Matlab in the RAM. In Matlab’s jargon this space is called the Workspace. • It also constantly looks at some specific directory on a designated permanent storage device – this is the Working Directory where your programs and input or output data files can be saved (permanently). To check what the working directory is you can type: pwd * • It translates instructions from the user to the computer and returns the result to the user in a format understandable to humans – this is the command interpreting function. * short for Print Working Directory

  19. CPU (executes instructions) Working directory (on a storage drive) Workspace (reserved memory space) Command Window USER Command line functioning diagram:

  20. Workspace – Notion of variable • The Workspace is the memory space in the RAM allocated to Matlab. It contains the variables that are currently used. • A variable is a name attached/allocated/assigned to a memory space (RAM) in which some data can be stored (for the time Matlab is running) • For example, entering A=4 assigns the numerical value 4 to the name or label or identifier “A”. This is an integer variable because 4 is an integer. • Example 2: day=’Wednesday’ assigns the string of characters Wednesday to the identifier day.

  21. Variable VARIABLE= Memory space containing a value Name (identifier) It is very useful to define variables – especially when the result from a long calculation is going to be re-used several times later or when its value depends on a user input.

  22. Types of Variables Variable can be of different type depending on the kind of ‘value’ they take. Most programming languages define the common data types: • Integer numbers e.g. 5 or -669 • Float number e.g. 3.111246E-8 • String of characters e.g. ‘MyStringOfCharacters’ • Array of numbers [1 -5 9 12 3.22 51 -65] • Structures made of other known types of variables • Boolean type (can only be 0 or 1)

  23. Managing the workspace • Defined variables appear in the Workspace frame together with their size and type. Typing the Matlab keyword who at the command line also lists the variables present in the workspace. • To remove a variable from the workspace (ie from memory) use clear. For example, typing >> clear A removes the variable A altogether so that it is no longer defined and its value is lost.

  24. Echo • Defining a variable or entering the name of an existing variable at the prompt causes Matlab to returns its value. This is called an echo. This can be useful to check its value but it can be stopped by typing a semi-colon after each instruction. • Example: when A=4; is entered, nothing is echoed but the assignment has still been executed as can be checked in the Workspace frame. • Semi-colon is also the statement delimiter in Matlab. It indicates that a statement is over and that what follows is a new one.

  25. A variable can be assigned the value of another variable: A=B; • Note that this equal sign represents an assignment and not an arithmetic equality – it is not a symmetric relation. It means “Erase whatever is already in A and put the value of B instead”. • This is very important – Say we want to write a short sequence of instructions which swaps the values between two variables A and B. First define the variables

  26. A=1;B=2; Then type A=B; B=A; Check the content of the variables is now: A=2, B=2. If you enter B=A; A=B; instead, the variable values are A=1, B=1. During an assignment, the value that the variable had before the assignment is lost.

  27. To solve the swapping problem, a third (auxiliary) variable must be introduced: C=A; %C is assigned the value of A ie 1 A=B; %A is assigned the value of B ie 2 B=C; %B is assigned the value of C ie 1 • Matlab ignores whatever is written after a % sign. This is used to make comments for ourselves or other potential readers. It is important to keep your programs well commented.

  28. Command History This frame simply lists the commands executed in chronological order. You can double click on any command in the list to re-run it or simply run through previous commands by typing the up-arrow key ↑ as many times as necessary at the command prompt. ■ Retrieve the command A=1 by the two methods

  29. Current Directory • This window is like a mini version of windows explorer. It helps identify where you files are. You won’t be creating any file for this session. You can change the working directory by typing >> cd whateverdirectory at the command line or double clicking on the directory you want in the window. • Now back to the Command Window…

  30. Matlab as a calculator • Matlab can work as a calculator: the command prompt can handle standard arithmetic operations. For example: >> 2+3 ans = 5 • By default, the result is put into a variable called “ans” which is short for answer.

  31. Arithmetic operations can be combined with assignments: >> A= 2+3 A = 5 >> B=4*A B = 20 >> C=A^B C = 3200000 Raising to a power is done with the operator “^”. A^2 gives 25

  32. Built-in constants and functions • There are a number of standard built-in constants. Type pi, e, i and see what you get. Be careful, these values can be overwritten. • There is also a vast number of built-in standard mathematical functions in matlab: >> sin(pi/2) ans = 1 Similarly cos, tan, asin, acos, atan… are predefined.

  33. Other built-in functions • sqrt(x) = square root of x • abs(x) = absolute value or modulus of x • sign(x) = sign of x; returns +1 or -1 • round(x) = rounds x to the nearest integer • exp(x) = exponential of x • log(x) = natural logarithm of x • log10(x) = logarithm of x in base 10 ■ Try task 4

  34. Vectors or arrays • Matlab is designed to work with arrays like vectors, matrices (two dimensional vectors). Even simple numbers are treated like 1x1 matrices. • To define a row vector, you can simple list its elements in square brackets separated by spaces: >> V1=[2.5 1 0.3 5] V1 = 2.5000 1.0000 0.3000 5.0000 • Defined this way, V is a row vector.

  35. To create a column vector, the element must be separated by semi-colons. >> V2=[2.5; 1; 0.3 ; 5] V2 = 2.5000 1.0000 0.3000 5.0000 The quote sign ‘ executes a matrix transpositions Check that what V1’gives.

  36. Accessing elements of arrays • To access the element of any array, normal brackets must be used: >> V(4) ans = 5 • These rules can be combined to define and access matrix elements. M=[cos(pi/4) sin(pi/4);-sin(pi/4) cos(pi/4)] M = 0.7071 0.7071 -0.7071 0.7071 >> M(2,2) ans = 0.7071

  37. Generating vectors with evenly spaced elements There is an extremely useful way of generating evenly spaced vectors: >> x=1:2:10 x = 1 3 5 7 9 • x is vector of integers starting from 1 up to at most 10 by increments of 2. • Increments of 1 are the default and can be omitted, ie 1:5 is the same as 1:1:5.

  38. Other misc. ways of creating vectors • Guess what these instruction will produce and check your result. Make sure you understand: >> a = [1:2:6 -1 0] >> b = a(1:2:6) >> c = [a(2:4) b]

  39. Accessing a range of matrix elements • The symbol colon “:” almost always means range in matlab. This can be used to access parts of a matrix: >> M(1:2,1) ans = 0.7071 -0.7071 Returned are the 1st elements in the first two columns of M

  40. Operations on Arrays – Addition • Arrays of the same size can be added. The addition is carried out element by element >>V3=[1 2 3 4 5]; >>V4=[5 4 3 2 1]; >>V5=V3+V4 V5 = 6 6 6 6 6 If you try adding arrays of different size, you get an error. Check this by entering >>V1+V2

  41. Operations on Arrays – Multiplications There are two types of multiplications for arrays: The operator “*” means matrix multiplication:>> [1 2 3 4]*[1; 2; 3; 4] ans = 30 The operator “.*” executes an element by element multiplication: >> [1 2 3 4].*[1 2 3 4] ans = 1 4 9 16 ►The same operations would take several lines of code in any other language

  42. Elements of a vector can also be raised individually to a power using the operator “.^” >> [1 2 3 4].^2 ans = 1 4 9 16 Without the dot, ^ is a matrix power operator (for square matrices) i.e. M^2=M*M To add a constant to every element of an array, simply use “+”: >> [1 2 3 4] + 3 ans = 4 5 6 7

  43. In fact the built-in functions introduced a few slides earlier work equally well on vectors and matrices: >>A=[0 pi/4 pi/2]; sin(A) ans = 0 0.7071 1.000 >>M2=[4 9; 16 25]; sqrt(M2) ans = 2 3 4 5

  44. Built-in matrix operations: Standard matrix operators are also built-in. For example the determinant: >> det(M) ans = 1 ■Define your own 3x3 matrix and get its determinant

  45. Getting help • For a quick check about how to use a Matlab keyword or built-in function you know exists, e.g. det simply type: >> help det • This also allows you to check that a variable name you want to use is not already a Matlab keyword (though the keyword iskeyword does just that). • More extensive help is available from the help window started by clicking on the question mark. From here, some keywords will be introduced without explanation – check them out!

  46. The Help Menu If you’d like to know if Matlab does something you need, you can try the help menu simply by typing: >>help This returns the full help menu. You can then narrow down your search using the short description. For instance: >> help elmat elmat is short of elementary matrices. ■ Check what the keywords rand and size do. ■ Spend a bit of time exploring the help menu to get a sense of the capabilities Matlab offers. Note: size is an important keyword to remember.

  47. Plotting Matlab is very power to produce and customise plots easily. The build-in command plot(xvect,yvect) joins by a line the points described by the x-coordinates and y-coordinates of the two vectors xvect and yvect. For example, try >> time=[0:0.01:2*pi]; >> ysine=sin(time); >> plot(time,ysine);

  48. Axis labels and a title can be added using the commands: >> title(‘Simple Plot’); >> xlabel(‘Time’); >> ylabel(‘Sine’); • Matlab tries to choose sensible extreme values for the axes. These can be overwritten using the command axis(v) where v=[Xmin Xmax Ymin Ymax] • Most plot properties can be edited from the plot window by clicking on the little diagonal arrow on the tool bar then clicking on any feature of the plot you’d like to edit (axis, curve thickness color…)

  49. ■ Now try Task 5

More Related