lecture 3 - matlab introduction cven 302 june 7, 2002

43
Lecture 3 - Matlab Lecture 3 - Matlab Introduction Introduction CVEN 302 June 7, 2002

Upload: dwain-norton

Post on 13-Dec-2015

219 views

Category:

Documents


2 download

TRANSCRIPT

Lecture 3 - Matlab IntroductionLecture 3 - Matlab Introduction

CVEN 302

June 7, 2002

Lecture GoalsLecture Goals

• Matlab files

• Matlab controls

M-filesM-files

These files load constants lists and executable

programs into memory. For example:

dir

myCon.m

type myCon

myCon or load myCon

Function M-filesFunction M-files

These files are similar to subroutines and will

act as built-in functions, i.e. a tool box similar

to functions, sin(x), log(x)

Open a new m-file

Function filesFunction files

Function “name”(input variables) function statements

There are set of example files show be in the working directory.

twosum(x,y)addmult(x,y)

(1)(2)

Function m-filesFunction m-files

The functions act similar to any of the built-in functions, sin(x), ln(x), etc. The inputs and outputs of the functions can be a variable, vector and/or a matrix.

Input function in m-filesInput function in m-files

Input function allows a program to input data into memory. The function is defined as:

variable = input(‘ string request ‘);

Example: inputAbuse.m file

Output functions in m-filesOutput functions in m-files

Output function allows a program to output data to screen. The function is defined as:

fprintf(‘ … %g\n‘,variable);

“%g” is a definition of type of variable“\n” causes a carriage return

Flow controlsFlow controls

There are three types of flow control devices.

• Relational Operations

• Arithmetic Operations

• Logistic Operations

Relational OperationsRelational Operations

Relational operations are

used for comparison of

different values and

generate a true/false

result.

< less than

<= less than or equal

> greater than

>= greater than or equal

== equal to

~= not equal

Logistic OperationsLogistic Operations

Logistic operations are

used to combine relational

operations to generate a

true/false result.

& and

| or

~ not

Relational and Logistic Relational and Logistic OperationsOperations

a=2; b=4;

Relational Operations

aisSmaller = a < b; % results in aisSmaller = 1 (true)

bisSmaller = b < a; % results in bisSmaller = 0 (false)

Relational and Logistic OperationsRelational and Logistic Operations

Logistic Operations

bothTrue = aisSmaller & bisSmaller % bothTrue = 0 (false)

eithTrue = aisSmaller | bisSmaller % eithTrue = 1 (true)

~eithTrue = 0 (false)

Operational PrecedenceOperational Precedence

– Arithmetic Operations

– Relationship Operations

– Logical Operations

Operational precedence means the hierarchy of the operators:

Operational Precedence exampleOperational Precedence exampleArithmetic Operations

x= 2 + 3^2/4 is:

x = 2 + ( 32 / 4 ) not x = 2 + 3(2/4)

So for Operational precedence

y = 3 > 8-3 | sqrt(15) >= 4

y = 3 > 5 | 3.873 >= 4 arithmetic operations

y = 0 | 0 relational operations

y = 0 logistic

Program flow controlsProgram flow controls

• “if … else …end” statements

• “switch” structure

• “for” structure

• “while” statements

““if” flow controlif” flow control

The if command can be

used to control the flow

of the program. There

are three basic forms of

the “if” controls.

if (relation expression)

:

block of statements

:

end

example : cond1.m

““if” flow controlif” flow control

The “if “ command can

be used with an “else”

command.

if (relation expression)

:

block of statements

:

else(relation expression)

:

block of statements

:

end

example :cond2.m and cond3.m

““switch” flow controlswitch” flow control

The “switch” command

can be used for multiple

case of the “if” command.

switch(relation expression)

case 1(value)

block of statements

case 2(value)

block of statements

case 3 (value)

block of statements

otherwise

:

end

example: cond4.m

““for” flow controlfor” flow control

The “for” command is

used to do a series of

steps of redundant

process.

for(index= #)

:

block of statements

:

end

example:

x= [4,5,6,7]; sumx = 0;

for k =1:length(x)

sumx = sumx + x(k);

end

““for” flow controlfor” flow control

The “for” command can

have various forms of

step sizes.

example:

(counter) = start:step:final

value size value

k = 1:2:n (1,3,5,…n)

m = 0:pi/15:pi (0,Pi/15,…,Pi)

k = n :-1:1 (n,n-1,…,1)

““while” flow controlwhile” flow control

The “while” command

can do redundant process

by checking on a logical

or relational operation or

combination of the two.

while(expression)

:

block statements

:

end

Example:

x = 4;

while (x-1)>= 0.01

x = sqrt(x);

disp(x);

end

Escape commandsEscape commands

• “break” is an escape from a loop, which will go the end of the loop and start the next step in the program.

• “return” is an escape from a program or subroutine or a function and return to the main program.

Misc. FunctionsMisc. Functions

• disp(expression) - displaces the expression to the screen.

• format (long,e,short, ...) determines the format of numerical values.

• ‘global variable’ makes a variable available in any function or program as shared memory.

Design Steps for a ProgramDesign Steps for a Program

• Design the code to do the problem – Input types – Output types

• Write up the code with modified comments.

• Test the code with a simple set of test examples.

• Document the code

Design of the M-filesDesign of the M-files

Remain consistent in how you put your

program together. Break it into parts:– Input information - comments and variables

definition and options & verify input parameters.

– Primary computational task– Output options (plot information, ascii,

filenames, etc.)

Program DesignProgram Design

• Visual blocking show the layout of the program.

• Whitespace in the text of the program.

• Meaningful variable names

• Documentation

Visual BlockingVisual Blocking

Which is easier to read?

n = length(x)

if mean(x) < 0

y(1) = 0; y(n) = 0;

for k=2:n-1

y(k) = x(k+1) - x(k-1);

end

else

y(1) = x(1); y(n) = x(n);

for k=2:n-1

y(k) = 0.5*( x(k+1) +

x(k-1));

end

end

How do you visualize your code?

n=length(x)

if mean(x)<0

y(1)=0;y(n)=0;

for k=2:n-1

y(k)=x(k+1)-x(k-1);

end

else

y(1)=x(1); y(n)=x(n);

for k=2:n-1

y(k)=0.5*(x(k+1)+x(k-1));

end

end

Whitespace layoutWhitespace layout

Which line is easier to read?

y(k)=0.5*(x(k+1)+x(k-1)); % or

y(k) = 0.5*(x(k+1)+x(k-1)); % or

y(k) = 0.5*( x(k+1) + x(k-1) ); % or

y(k) = 0.5 * ( x(k+1) + x(k-1) );

Variable NamesVariable Names

Use variable names, which have meaning so you can read the code and understand it.

Variable typical code meaningful code

inside diameter d=5; ins_diam = 5;

thickness t=0.02; thickness = 0.02;

inside radius r=d/2; ins_radius = ins_diam / 2;

outside radius r2=r+t; out_radius = ins_radius +

thickness;

DocumentationDocumentation

Documentation is critical for any code that is not going to be used and immediately discarded. Documentation takes the form of comment statements that describe the input and output parameters of a function as well as the steps performed in the analysis.

Documentation RecommendationsDocumentation Recommendations**

• If a program is incorrect, it matters little what the documentation says.

• If documentation does not agree with the code it is not worth much.

• Consequently, code must largely document itself. If it cannot, rewrite the code rather than increase the supplementary documentation. Good code needs fewer comments than bad code does.

Documentation Recommendations*Documentation Recommendations*

• Comments should provide additional information that is not readily obtained from the code itself. Comments should never parrot the code.

• Logical variable names and labels, and layout that emphasizes logical structure, help make a program self-documenting.

* Kernighan and Plaugher, The Element of Programming Style, 1978

InputInput

Function definition

• Summary is what the program does.

• Synopsis run program

• Input definition of terms

• Output what type of output

• Notes

Input ExampleInput Examplefunction rho = H2Odensity(T,units)

% H2Odensity Density of saturated liquid water

%

% Synopsis: rho = H2Odensity

% rho = H2Odensity(T)

% rho = H2Odensity(T,units)

%

% Input: T = (optional) temperature at which density is

% evaluated:Default: T= 20 C If units = F

% then T is degrees F

% units = (optional) units for input temperature,

% Default = ‘C’, units= ‘C’ for Celsius

% units = ‘F” for Fahrenheit

%

% Output: rho = density, kg/m^3,if unit = ‘C’ or lbm/ft^3 if

% unit =‘F’

%

% Notes: Use 4th order polynomial curve fit of the data in

% Table B.2 of ‘Fundamental of Fluid Mechanics’

Organization of Numerical MethodOrganization of Numerical Method

Start with an abstract or verbal description of a

computational task, it will be necessary to develop a

sequence of smaller tasks that can be implemented

sequentially.

Stepwise refinement is designed to break up a large

task into a set of smaller tasks. The same procedure

is called ‘top-down design’ or ‘divide and conquer’.

Implementation and TestingImplementation and Testing

Break the problem into small modules/segments of

code, which you can test.

Testing

It is important to verify that m-files are working correctly before they are used to produce results that inform other decisions. The best check on any calculation, be it manual or automatic, is by an independent test. One which you have to designed.

DebuggingDebugging

Searching for and removing bugs is an inevitable part of programming. Bugs are caused by a number of factors from outright programming blunders to the improper application of numerical method.

Defensive ProgrammingDefensive Programming

• Do not assume that the input data are correct. Test them.

• Guard against the occurrence of an impossible condition that would cause a failure in a calculation.

• Provide a catch or default condition for a sequence of if … elseif … else … constructs.

• Provide diagnostic error messages that will help the user determine why the function failed to complete it calculation.

Debugging ToolsDebugging Tools

• type and dbtype commands– type prints out the file error– dbtype will print out the file with line numbers.

‘dbtype start:stop’ will print out lines from start to stop.

• Error function - error(message) will print out the message and halt execution.

Debugging ToolsDebugging Tools

• ‘pause’ command temporarily suspends the execution of the m-file. Useful way to print a warning message without necessarily aborting an analysis.

• ‘keyboard’ command keyboard command suspends execution of an m-file and gives control to user. It gives the user access to internal variables of the function containing command.

Debug exampleDebug example

The example program:

‘keyboard’ stops a program to check internal

variables. It is a powerful tool.– ‘ K>> ‘ is the prompt and you can use it to

check numbers out.– ‘K>> return’ will return to the executable

program.

HomeworkHomework

• Check the Homework webpage.

• You will be writing a simple program to generate a set of points and generate a plot.