Sunteți pe pagina 1din 31

MH 1400

ALGORITHMS &
COMPUTING I
Asst. Prof. Axel POSCHMANN
AY 2012/13 Semester 1

04.09.2012 Lecture 4: Scripts

4/9/12

Lecture 4: Scripts

L4-2

MH 1400 Algorithms & Computing I


Outline

Algorithms
MATLAB scripts
Documentation
Input
Output
Printing Vectors and Matrices
Scripts with Input and Output
Lessons Learned

4/9/12

Lecture 4: Scripts

L4-3

Algorithms
Definition:
An Algorithms is the sequence of steps needed to
solve a problem.

4/9/12

Lecture 4: Scripts

L4-4

Top-Down Approach
Top-Down Design approach:
Break down the problem solution into separate steps
Refine each step until they are small enough to be manageable
tasks
Example: calculate the area of a circle:
1. What information is required?
radius
2. Given the radius, calculate the area
area = 2*pi*radius
3. Display the output

4/9/12

Lecture 4: Scripts

General sequence for algorithms


1. Get the input(s)
radius
2. Calculate the result(s)
area = 2*pi*radius
3. Display the result(s)

L4-5

4/9/12

Lecture 4: Scripts

Further Refinement
1. Where does the input come from?
External file
One of them is the default input device
User
Input is now two steps:
1. Prompt the user to enter data
2. Read data into program

Default input device is either external file or user.


Prompting means telling the user what to enter.

L4-6

4/9/12

Lecture 4: Scripts

L4-7

Further Refinement (ctd)


2. Value of constant PI is required.
3. Where does the output go?
To an external file
To the screen

Always print the output as informative as possible!


Also include the input.
Examples
Bad:
>> 3.1416
Good:
>> The area of a circle with radius 1 is 3.1416

4/9/12

Lecture 4: Scripts

L4-8

MATLAB Scripts
Definition: Interpreter
Goes through the code line-by-line
Executes commands as it goes
MATLAB interprets script files (also called M-files)
A program is a set of scripts and functions.
A script is a sequence of MATLAB instructions that is

stored in an M-file.

4/9/12

L4-9

Lecture 4: Scripts

M-files
Used to store scripts
Can be displayed by the type command
Can be edited by the edit command
Can be executed by entering its name at the prompt

>> type example


>> edit example
>> example

to display
to edit
to run

4/9/12

Lecture 4: Scripts

Creating Scripts
2 simple steps to create a script:
Check that the current folder is correct
Either Click File -> New -> Script or
Press ctrl+N or
Type edit

Naming conventions for scripts


Same as for variable names, i.e.
the name must start with a letter,
then letters, numbers or underscore)

The name must end with .m

L4-10

4/9/12

Lecture 4: Scripts

L4-11

Documentation
It is very important to document scripts well, so that

others can understand it.


Use comments frequently and extensively to describe in
detail what your script do.
% is used to comment anything from here until the end of
the line
First block of comments (contiguous lines at the
beginning) will be used for the help command.
The very first command line is called H1 line.
The function lookfor searches through the H1 lines of
all M files.

4/9/12

L4-12

Lecture 4: Scripts

Input
Input statements read in values from the standard input

(which is the user)


input function is used in an assignment statement
Example:
>> read = input(Enter the radius: )
User provided
Input is stored
in this variable

Prompt
this is what the user
will see on the screen

4/9/12

Lecture 4: Scripts

L4-13

Input
If you want to read in a character or a string you have two
options:
either add s to the input function
>> letter =input(Enter a character: ,s)
Or add quotation marks around your input
>> name=input(Enter your name: )
Enter your name: Anonymous
name =
Anonymous

Better!

4/9/12

Lecture 4: Scripts

L4-14

Input (ctd)
Note: it is better to use option 1) because the user may

not be aware that he has to add quotation marks.


If s is specified in the input function and the user still
uses the quotation marks, they are also included in the
string
Example:
>> name=input(Enter your name: ,s)
Enter your name: Anonymous
name =
Anonymous

4/9/12

Lecture 4: Scripts

L4-15

Input (ctd)
If MATLAB expects a number, but a letter is input it throws

an error message and repeats the prompt


If the letter is the name of a variable, then it works as well
Example:
>> t = 23;
>> num=input(Enter a number: )
Enter a number: t
num =
23

4/9/12

Lecture 4: Scripts

L4-16

Input (ctd)
Separate input statements are necessary if more than

one input is desired.


Example:
>> x=input(Enter the x coordinate: );
>> y=input(Enter the y coordinate: );

4/9/12

Lecture 4: Scripts

L4-17

Output
Output statements display strings and/or the results of

expressions and can allow for formatting or customizing


how they are displayed.
Disp
Is the simplest output function
Does not allow formatting
Does not assign a value to ans
>> disp(Hello World!);
Hello World!

4/9/12

L4-18

Lecture 4: Scripts

Output (ctd)
fprintpf
Allows to print formatted output on the screen
Uses a format string to format the output
Format information,
place holder

newline
character

>> fprintf(The value is %d, for sure!\n,4^3)


format string

The value is 64, for sure!

4/9/12

Lecture 4: Scripts

L4-19

Output (ctd)
The character in the place holder is called the conversion

character. (In our example d)


Conversion characters (simple subset):
%d integer
%f float (real number)
%c single character
%s string
Note: Do not confuse the % in the place holder with the

symbol used to denote comments!

4/9/12

L4-20

Lecture 4: Scripts

Output (ctd)
A field width can be included in the place holder
At least 3 places
are reserved for
this expression

6 places (including the .)


and 2 decimal places
are reserved

>> fprintf(The int is %3d and the float is %6.2f!


\n,5,4.9)
The int is
5 and the float is
4.90!
Leading blanks and trailing zeros are used to match the given
format
The expressions fill in for the place holders in sequence

4/9/12

Lecture 4: Scripts

Output (ctd)
Other formatting options:
Left-justification by inserting a minus sign, e.g. %-5d
String truncation by specifying decimal places, e.g. %.2s
Special characters
Slash \
\\
Tab
\t
Quote

L4-21

4/9/12

Lecture 4: Scripts

L4-22

Printing Vectors and Matrices


For a vector, if a conversion character and the newline

character are in the format string, it will print in a column


regardless of whether the vector is a row vector or a
column vector.
>> vec = 2:5;
>> fprintf(%d\n,vec)
2
3
4
5

4/9/12

Lecture 4: Scripts

L4-23

Printing Vectors and Matrices (ctd)


Without the newline character, it will print in a row (but

messy end!)
>> fprintf(%d,vec)
2345>>
Using a script it is possible to separate numbers with

spaces and to start the prompt in a new row (better)


>> fprintf(%d ,vec)
>> fprintf(\n)
2 3 4 5
>>

4/9/12

Lecture 4: Scripts

L4-24

Printing Vectors and Matrices (ctd)


If numbers of elements is known, one could use that many

conversion characters and then the newline


>> fprintf(%d %d %d %d\n,vec)
2345
>>
Not very general, hence not advised!

4/9/12

Lecture 4: Scripts

L4-29

Lessons learned
Common Pitfalls:
Spelling a variable name different ways in different places
in a script or function.
Forgetting to add the second s argument to the input
function when character input is desired.
Not using the correct conversion character when printing
Confusing fprintf and disp. Remember that only
fprintf can format.

4/9/12

Lecture 4: Scripts

L4-30

Lessons learned
Programming Style Guidelines:
Especially for longer scripts and functions, start by writing
an algorithm
Use comments to document scripts and functions, as
follows:
Block of contiguous comments at the top to describe a script
Block of contiguous comments under the function header for

functions
Comments throughout any M-file (script or function) to describe
each section

4/9/12

Lecture 4: Scripts

L4-31

Lessons learned
Programming Style Guidelines:
Make sure that the H1 command line contains useful
information
Make all output easy to read and informative
Put a newline character at the end of every string printed
by fprintf so that the next output or the prompt
appears on the line below

S-ar putea să vă placă și