a reintroductiontomatlaband making...
TRANSCRIPT
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
AERO 325 Coding TutorialA Reintroduction to Matlab and Making
Code Readable and ScalableDerek J. Dalle
University of Michigan, Ann Arbor, MI 48109
Fall 2012
AERO 325 Coding Tutorial, Using functions 1/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
What to get out of this tutorialStart writing programs like this!
z
Streamlineplotter
FIGURE
F(z)
w(z)
z0Source
Q
LEGEND
x
Source
FIGURE
Input/Output
Function
Figure or plot
Information flowAERO 325 Coding Tutorial, Using functions 2/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
What do you mean, “Program like this?”
Things I don’t mean
Use SIMULINK
Draw a bunch offlowcharts everywhereyou go
Really just this
Use functions!
Write modular code thatcan be upgradedwithout starting over
Your programs shouldbe easy to understandand read
z
Streamlineplotter
FIGURE
F(z)
w(z)
z0Source
Q
LEGEND
x
Source
FIGURE
Input/Output
Function
Figure or plot
Information flow
AERO 325 Coding Tutorial, Using functions 3/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
This is what engineers usually do.
FIGUREMY FUNCTION
AERO 325 Coding Tutorial, Using functions 4/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
Why do you want us to do that?
z
Streamlineplotter
FIGURE
F(z)
w(z)
z0Source
Q
LEGEND
x
Source
FIGURE
Input/Output
Function
Figure or plot
Information flowAERO 325 Coding Tutorial, Using functions 5/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
Why do you want us to do that?Construct more complicated flows using most of the same code
z
Streamlineplotter
FIGURE
F(z)
w(z)
z1Source
Q1
z2Source
Q2
z3Vortex
Γ3
αFreestream
U∞
Combined stream function
AERO 325 Coding Tutorial, Using functions 5/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
Why do you want us to do that?Many panels plus a freestream velocity
z
Streamlineplotter
FIGURE
F(z)
w(z)
αFreestream
U∞
z1,...,zn
Q1,...,QnSource
AERO 325 Coding Tutorial, Using functions 5/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
The goal of today’s tutorialThis is only a small modification from the previous slide.
Q1,...,Qn
Normalvelocity
w1,...,wn
Linearsolver
vN1,...,vNn
Sorry this is so crowded!
The lesson: The combination of these blocks is a function that takes z1, ..., zn along with α and U∞ and returns a set of source strengths.
αFreestream
U∞
z1,...,zn Unit source
AERO 325 Coding Tutorial, Using functions 6/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
Laundry listBasically my priorities on good (or at least readable) Matlab coding
General
Basic mechanics(Editor/command line)
Functions and not scripts!
The little orange marks on theside are your friend
Debugging
Coding basics
Declaring a function with inputsand outputs
for loops
Basic vectors/matrices
Handling exceptions
Vectorizing code
Can always go without this, butit makes life much easier (foryou and your computer)
“Dot” operators, .*, .^, etc.
Initializing vectors and matrices
Aerodynamics
If you do everything just right, thecode you can write today can bemodified to make any 2D panelcode. The method we will use isparticularly bad.
AERO 325 Coding Tutorial, Using functions 7/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
AgendaThe farther we get, the easier your next homework will be
We’ll be going back and forth between me talking and you coding.
1 Basic introduction (this) (20 min)2 Matrix construction example (ex1.m) (5 min)3 Tips not directly about code or syntax (5 min)4 FUNCTIONS, function syntax, input, and output (5 min)5 Potential functions for point source and freestream (ex2.m) (5 min)6 Introduction to vectorization! (5 min)7 Lots of sources plus one freestream (ex3.m) (10 min)8 Writing readable code and when to use loops (5 min)9 Create a point-source panel code (ex4.m) (whatever’s left)
Please follow the instructions within the example files (ex1.m, etc.)about naming new files.
AERO 325 Coding Tutorial, Using functions 8/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
Vectors and MatricesIntroduction
In Matlab, scalars, vectors, and matrices are really all the same thing.
Suppose A is a matrix, x is a columnvector, and c is a scalar. You can usethe size command to find out how manyrows and columns each variable has.
>> size(A)ans =
5 4>> size(x)ans =
4 1>> size(c)ans =
1 1
To see the value of one entry of a matrixor vector, use the following notation
>> A(2, 3)ans =
-1
This is the third entry of the second row.Use this to change a single entry of amatrix, too.
>> A(2, 3) = 4;>> A(2, 3)ans =
4
AERO 325 Coding Tutorial, Using functions 9/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
Creating vectors and matricesThe right way
Small arrays
For a small vector or matrix, if you know all the values, construct it directly.
A = [1, 0; 2, -1; 3, 0];
Use commas to separate entries within a row and semicolons to separate rows.
Large arrays
Initialize large arrays to the correct size using a vector command. This creates amatrix of all zeros with 100 rows and 20 columns.
A = zeros(100, 20);
See also the commands ones, eye (identity matrix), and nan (not a number).Matlab will let you get away with not doing this, but it’s a really bad idea!
AERO 325 Coding Tutorial, Using functions 10/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
Creating a large matrix or vectorObviously a big matrix full of zeros is not that interesting
1 Decide how many rows and columns you need.
m = 21; n = 21;2 Initialize the matrix and/or vector.
A = zeros(m, n); b = zeros(m, 1);3 Now loop through the rows and columns to set the entries to what
you really want.
for i = 1:mfor j = 1:n
A(i, j) = ???endb(i) = ???
end4 Suppose you want each entry in the kth row to be 1.
A(k, :) = 1;5 Use this to solve the linear system Ax = b
x = A \ b;AERO 325 Coding Tutorial, Using functions 11/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
Problem 1Create a specified linear system
Open the files ex1.m and make_matrix.m in Matlab.
The files contain the instructions that you need. Your task is to create thematrix and vector
A =
1 −1 0 0 0 0−1 2 −1 0 0 00 −1 3 −1 0 00 0 −1 4 −1 00 0 0 −1 5 −10 0 0 0 −1 6
b =
123456
but for arbitrary size. This would be for n = 6.
Then you must solve the linear system Ax = b.
AERO 325 Coding Tutorial, Using functions 12/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
Matlab code checker (formerly called MLint)Matlab is surprisingly good at improving your code
On the right-hand side of any fileopened in the Matlab editor there isa helpful bar. The top right cornerhas a box that gives a quicksynopsis of your code. This is reallyhelpful; try to make the squaregreen!
Bad (code will not run):
Better (problems detected): Good (doesn’t mean perfect):
AERO 325 Coding Tutorial, Using functions 13/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
Matlab code checker (formerly called MLint)Individual suggestions
The rest of the bar gives an individuallisting of each error or suggestion thatMLint has found in your file. You canmouse over a mark to read MLint’ssuggestion or click on the mark to takeyou to the line with the problem.
It’s not always possible to get rid of allthe orange marks, but you shouldcertainly consider each suggestion. A lotof errors, like variables that are neverused, are trivial to fix.
Sometimes MLint suggests a correctionon its own.
Each mark represents an error orsuggestion.
AERO 325 Coding Tutorial, Using functions 14/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
DebuggingCode doesn’t work? Put a break point right before the error.
The bar on the left side of the editor is for breakpoints. The program will stop each time it gets to aline with a red dot to the left of it. You can add andremove the break points (red dots) by left-clicking onthem one time.
Once you’re at a break point, you can see the valuesthat each variable has and use them from theMatlab command line.
Debugging toolbar
Just click on these buttons while in debug mode;you’ll quickly figure out what they all do and whenthey’re useful.
AERO 325 Coding Tutorial, Using functions 15/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
FunctionsHow to use them
1 Create a file for each function. (Just like you are probably used todoing) (This example: mypotential.m)
2 Define the inputs and outputs with the first line in your file.
function [F, w] = mypotential(x, y)......
3 The inputs are x and y, and the outputs are F and w. You can haveas many inputs or outputs as you want.
4 Code the rest of the program the way you normally would (exceptdon’t define x and y; their values are taken from outside).
AERO 325 Coding Tutorial, Using functions 16/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
Functions (and not scripts)Why to use them
Reusability and Readability
Suppose you have to do a complicated task that you need to do many times.
A = point_source(z, z1, Q1) + point_source(z, z2, Q2);
Suppose you made a small mistake in your function. Now you only need to fix itin one place! It’s also far easier to understand what’s going on (including to you!).
Scripts are bad!
Scripts have global scope–which means they affect variables outside thefunction. Consider this example where my_dumb_script is a file that begins withthe command clear all and then does some other task.
>> F = complicated_model(1e10); % This might take hours.>> my_dumb_script>> FUndefined function or variable 'F'.
It’s gone! Never put clear all in your programs!!!!!!AERO 325 Coding Tutorial, Using functions 17/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
Problem 2
Open the file ex2.m in Matlab.
The file contains the instructions that you need. Your task is to create twocomplex potential functions: point_source.m for a source centered atz0 with strength Q and freestream.m for a freestream velocity of U atan angle of α. The main purpose of this task is to practice creatingfunctions.
OUTPUT 1 OUTPUT 2 NAME INPUT 1 INPUT 2 INPUT 3F w point_source z z0 QF w freestream z U α
Point source:
F(z) =Q2π
log(z− z0) w(z) =Q
2π(z− z0)
Freestream:
F(z) = Ue−iαz w(z) = Ue−iα
AERO 325 Coding Tutorial, Using functions 18/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
VectorizationApplying operations to vectors and matrices to get rid of loops
Have you ever noticed what happens when you use a function like sinon a matrix? It turns out that
>> sin([1, 0.5; -2, 3])ans =
0.8415 0.4794-0.9093 0.1411
is exactly the same as
>> [sin(1), sin(0.5); sin(-2), sin(3)]ans =
0.8415 0.4794-0.9093 0.1411
This is exactly what we would want, and it means we don’t have to writeas many loops.
AERO 325 Coding Tutorial, Using functions 19/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
VectorizationApplied to your code: the so-called “dot operators”
This is the key to writing fast code in Matlab.
Compare two versions that calculate the following formula for eachelement of two m×n matrices
z = x2 siny
Bad versionfor i = 1:m
for j = 1:nz(i,j) = x(i,j)^2*sin(y(i,j))
endend
Good versionz = x.^2 .* sin(y)
This is simpler to write, easier to read, and much faster. It’s a good habitto always use dot operators (except .+ and .-, which are the same).
AERO 325 Coding Tutorial, Using functions 20/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
Vectorization and Problem 2
Think about the point_source function you wrote for Problem 2.
(1) Does it work if z is a matrix and z0 and Q are both scalars?
(2) Does it work if z is a scalar and z0 and Q are both vectors?
Test it!
Most likely the answer to (1) is yes, and the answer to (2) is no. Can youmake a very small change to your code so that both are true?
AERO 325 Coding Tutorial, Using functions 21/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
Problem 3A freestream with several sources and sinks
Open the files ex3.m and multi_source.m in Matlab.
The files contain the instructions that you need. The task is to create ageneric complex potential function that can plot the streamlines for onefreestream plus any number of of sources and sinks (and vortexes?).
It’s ok to use a loop for this one!
Your folder contains a function to plot the streamlines automatically. Runex3.m to test your file. If you have done everything correctly, you shouldget a streamline plot for what looks like a wavy symmetric airfoil.
x
y
−5 −4 −3 −2 −1 0 1 2 3 4 5−1
−0.8
−0.6
−0.4
−0.2
0
0.2
0.4
0.6
0.8
1
AERO 325 Coding Tutorial, Using functions 22/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
CommentsSelf-documenting source code
The things we’ve covered will do a lot to make code more readable.
But there’s one thing more important than all the rest: comments.
It doesn’t take very long, and there’s no reason not to comment every line!
Ok, I thought of two reasons
1 You want to make people figure out your code as an assignment
2 You want to put a short code snippet into a document
It’s better to put comments on their own line. Compare:
% Complex potential and velocity functions for source i.[F, w] = point_source(z, z0(i), Q(i));
[F, w] = point_source(z, z0(i), Q(i)); % source i
Use blank lines
In Matlab, two percent signs, %%, is a special type of comment that you canuse to split your code into blocks.
AERO 325 Coding Tutorial, Using functions 23/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
Example with lots of commentsThis function is hard enough to edit with comments
AERO 325 Coding Tutorial, Using functions 24/25
-
AERO 325 CodingTutorial
Dalle
Introduction
Motivation
Goal
List
Vectors andMatrices
Problem 1
MLint
Debugging
Functions
Problem 2
Vectorization
Problem 3
Readability
Problem 4
Problem 4A point-source panel method?
Open the files ex4.m and source_panel.m in Matlab.
The instructions in those files should be adequate, but this color-codedpicture may help. Or it might be really confusing.
U
α ni
U
AERO 325 Coding Tutorial, Using functions 25/25
IntroductionMotivationGoalList
Vectors and MatricesProblem 1MLintDebuggingFunctionsProblem 2VectorizationProblem 3ReadabilityProblem 4