introduction to programming using matlab session 2 p duffourjan 2008

24
Introduction to Programming using Matlab Session 2 P Duffour Jan 2008

Upload: miracle-varnum

Post on 31-Mar-2015

225 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

Introduction to Programming

using Matlab

Session 2

P Duffour Jan 2008

Page 2: 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).

Page 3: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

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.

Page 4: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

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

Page 5: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

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

Page 6: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

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.

Page 7: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

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.

Page 8: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

■ Now try task 2…

Page 9: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

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

Page 10: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

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

Page 11: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

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.

Page 12: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

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.

Page 13: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

Now try task 4

Page 14: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

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)

Page 15: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

Conditional Statements:

• Matlab has two main types of conditional statements:

– if… then (else)… end

– switch….case… end

Page 16: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

If…then… end

• The syntax for the simplest if-statement is:

if <condition is true>

do action1;

do action2;

end;• Note: there is no need to write ‘then’ in Matlab

although it is understood. • <condition is true> is a Boolean test

Page 17: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

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 true1==0 This 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.

Page 18: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

Boolean operators in Matlab

Symbol Meaning Example

==

~=

>

>=

<

<=

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

Page 19: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

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 ?

Page 20: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

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;

Page 21: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

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;

Page 22: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

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;

Page 23: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

Example of using switch

day=4; %This corresponds to Thursday=4th day %after Monday

switch daycase 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.

Page 24: Introduction to Programming using Matlab Session 2 P DuffourJan 2008

Now try task 6…