Presentation on theme: "Introduction to Programming using Matlab Session 2 P DuffourJan 2008."— Presentation transcript:
Introduction to Programming using Matlab Session 2 P DuffourJan 2008
To try not to overload the system, you will be working in pairs for this session Before starting Matlab, try Task 1 (you can use the first session power point presentation to help you with this task).
Writing a program in Matlab For more complex tasks than simple calculations or plots, writing commands line by line at the command prompt becomes quickly tedious. You can ‘feed’ Matlab with a whole sequence of commands at a time by writing a Matlab programme. Programmes written for Matlab are called m-files because they take the extension.m Because Matlab is a scripting language, m-files are also sometimes scripts.
Matlab editor Like any other source code, Matlab programmes (m-files) are simply text files so you can use any text editor to read and edit them. However the Matlab environment includes its own editor which offers useful capabilities that other non-dedicated editors do not. 3 ways to open a new m-file using Matlab editor –Type >> edit myprogram.m at the command prompt –Click on the blank page on Matlab main window toolbar –Click File → New → M-file
M-files Once the file is open with the editor, you can write matlab commands in it. For instance the three lines: x=0:0.1:4*pi; y=sin(x); plot(x,y); To execute them, save and name the file then type the name of the file at the command prompt (you don’t need to type the extension). For instance: >>myprogram or >>myprogram.m
M-files (cont) This will only work if you have saved your m-file in the ‘working directory’ – the directory where Matlab first looks to execute programs. You can check the working directory in the current directory frame (shared with Workspace) or by typing >>pwd Programs can also be executed directly from the editor by clicking the buttom showing an arrow down next to a page on the editor toolbar. ■Now change the range in the previous script so that it goes up to 6π and re-run the script.
Commenting Comments can be added to a program in Matlab using the sign ‘ % ’. Matlab ignores whatever comes after this sign on the same line. For example: x=0:0.1:2*pi %Defines a vector from 0 to 2pi by 0.1 steps You can write whatever you like after %. Commenting using the command line does really make sense but it is important to comment m-files. Commenting is very important and is essential to any programming. From now on, all your m-files should be commented.
Saving/Loading variables and data In session 1, it was said that variables in the workspace only last the time Matlab is running. Sometimes it is useful to save some results from a long calculation for future use or to use data obtained by some other means (e.g. some experiment). Data can be saved with Matlab using the keyword save. For example: >> V=rand(200) (check the help for rand ) >> save V
Saving/Loading (cont.) Check in the working directory (it might need refreshing) and a new file V.mat should have been created. The extension.mat is used for Matlab data files. You can clear the variable V from the workspace using clear V. This wipes the variable but the file V.mat will remain unless you delete it like any other file. Mat-files can be read using the keyword load e.g: >> load V.mat will bring the variable V in memory. ■ Now try task 3
User keyboard input When Matlab runs an m-file, it is not as easy to interact with the flow of instructions as it was when typing them line by line at the command prompt. Loading/Saving data-files is one way to get your program to interact but sometimes it is useful to ask the user for an input as you did with the ConvertTime.exe program last time. In Matlab, the keyword for the user to input some information via the keyboard during the execution is input.
Variable = input(‘ question to the user? ’) ; The line above shows how to use the keyword input. Such a statement will cause Matlab to display ‘question to the user?’ at the command line (or whatever you chose to write between the quote signs) It will wait for an answer. Once the return key is pressed by the user, it will store the answer into Variable.
Programming Constructs Programming constructs are logical elementary operations that allow you to carry out more complex tasks in programming. All programming languages have them in one form or another. They fall in two main categories: –Conditional statements (do that if this happens) –Loops (repetition of a task)
Conditional Statements: Matlab has two main types of conditional statements: –if… then (else)… end –switch….case… end
If…then… end The syntax for the simplest if -statement is: if do action1; do action2; … end; Note: there is no need to write ‘then’ in Matlab although it is understood. is a Boolean test
Boolean expressions Boolean expressions are simple logical statements which can be either true or false (there is no in-between in computing). Examples: 4<5 This is true 1==0This is false. The double == means that this is an equality test and not a variable assignment which is the other type of statement that uses the equal sign =. If you type these statements at the command prompt, you will get the answer 1 for the first and 0 for the second. In computing 1 means true and 0 means false.
Boolean operators in Matlab SymbolMeaningExample == ~= > >= < <= equal not equal strictly greater than greater than or equal to strictly smaller than smaller than or equal to if x==1 if x~=0 if x>y if x>=c if x<18*s if x<=11 &¦~&¦~ AND OR NOT if (x==1)&(y>3) if (x==1)|(y>3) if x~=y ►The operators AND, OR, NOT allow you to combine simpler tests
Simple example: a=1;b=0; if a>b c=3; disp(‘hello, the logical test is true’) end; ■What would be happen if this sequence was executed? What if a=1 and b=2 ?
if… then…else… end There is a straightforward extension to the simplest if…then…end. It works as follows: if u==a disp(‘u is equal to a’); else disp(‘u is not equal to a’); end;
Now try Task 5… if -constructs can be interleaved: if a==b if b==0 disp(‘b=0’); end; else disp(‘b is not equal to a’); end;
Switch-case Selection Switch conditional structures is particularly useful when dealing with some kind of menu where a variable can take a set of values and various actions must take place accordingly. The syntax is: switch variable case value1 do this case value2 do that … end;
Example of using switch day=4; %This corresponds to Thursday=4 th day %after Monday switch day case 1 %this effectively means if day==1 disp(‘Today is Monday); case 2 % i. e. if day==2 disp(‘Today is Tuesday’); … otherwise disp(‘The number should be between 1 and 7’) end; ► Note: The otherwise statement is optional. If it isn’t there and the variable doesn’t take any of the case values tested then Matlab reaches end and nothing has happened.