MATLAB Coding CHEN 1703 My thanks to my colleagues for their contributions to this lecture: Dr. James Sutherland, Dr. Leonard Pease, Dr. Michal Hradisky
Jan 26, 2016
MATLAB CodingCHEN 1703
My thanks to my colleagues for their contributions to this lecture:
Dr. James Sutherland, Dr. Leonard Pease, Dr. Michal Hradisky
ChEn 1703
Engineering ApproachFundamental
conservation lawsApproximations
& models
Algorithm (set of steps to
obtain an answer)
Solve by hand (pencil & paper,
calculator)
Solution
Numerical tools (help generate plots, calculate numbers)
MATLAB
Excel
Two engineering problems
What is the energy in/energy out ratio for in situ production of oil from shale?
!
!
!
!!
!
Data analysis - Using the right tool for the job
Two engineering problems
What is the energy in/energy out ratio for in situ production of oil from shale?
!
!
!
!!
!
Data analysis - Using the right tool for the job
250 m
450 m125 m
Two engineering problems
What is the energy in/energy out ratio for in situ production of oil from shale?
!
!
!
!!
!
Data analysis - Using the right tool for the job
Energy In (x10(kWh)
Oil Yield (m
Oil equivalent Energy Out (x10
NG equivalent Energy Out (x10
(kWh)
Case 1 13.9 592 6.33 6.84
Case 2 27.3 1,175 12.6 13.6
Case 3 43.2 1,120 12.0 12.9
Two engineering problems
What is the energy in/energy out ratio for in situ production of oil from shale?
!
!
!
!!
!
Data analysis - Using the right tool for the job
Energy In (x10
Oil Yield (m
Oil equivalent Energy Out (x10
NG equivalent Energy Out (x10
Energy In/Energy Out
Case 1 13.9 592 6.33 6.84 2.03 - 2.20
Case 2 27.3 1,175 12.6 13.6 2.00 - 2.17
Case 3 43.2 1,120 12.0 12.9 3.35 - 3.60
Two engineering problems
How does the NOx data from the simulation compare with the experimental data?
!
Data analysis - Using the right tool for the job
Two engineering problems
How does the NOx data from the simulation compare with the experimental data?
!
Data analysis - Using the right tool for the job
Two engineering problems
How does the NOx data from the simulation compare with the experimental data?
!
Data analysis - Using the right tool for the job
Port Location : 1
Probe Insertion Distance (" in from tile) Pressure Temperature O2 CO NO NO2 NOx
1 0.30 920 0.49 4470 9.4 0.0 9.44 0.40 930 0.44 4634 10.6 0.0 10.6 Temp = F7 0.70 930 0.40 4804 11.3 0.0 11.3 Dry, vol% O210 0.70 970 0.41 4671 11.0 0.0 11.0 `13 1.00 990 0.40 4628 11.5 0.0 11.5 (As corrected to 3% O2 by volume not done; numbers are raw)16 1.00 1040 0.42 4356 11.5 0.0 11.5 Number representspseudo-steady state reading after extracting for some period of time19 1.00 1070 0.39 4288 11.8 0.0 11.8 No replications22 1.20 1100 0.41 4547 11.7 0.0 11.7 Chevron ran @ fixed firing rate, not fixed steam quality25 1.20 1120 0.45 4586 11.4 0.0 11.428 1.40 1140 0.44 4505 11.1 0.0 11.131 1.40 1160 0.66 2929 9.7 0.0 9.734 1.30 1180 0.66 3039 9.5 0.0 9.537 1.20 1190 0.58 3993 11.4 0.0 11.440 1.20 1240 0.60 4561 11.3 0.5 11.843 1.20 1280 3.29 5000+ 6.1 1.5 7.646 1.20 1400 13.73 2864 2.2 2.8 5.049 0.5 1380 9.53 1320 2.0 5.8 7.852 0.7 1370 8.06 12 8.5 4.8 13.355 1.2 1780 7.95 7 8.3 4.5 12.858 1.3 1800 8.02 6 7.0 4.3 11.361 1.3 1835 8.16 5 5.6 3.8 9.4
62.5 (center of radiant section) 1.2 1855 8.25 4 4.7 3.5 8.2
Radiant Section Pressure Probe (Probe 1)
1 1/2 ft from burner endTime Stamp: 10:00 AM 2/20/07
Two engineering problems
How does the NOx data from simulation compare with experimental data? Solution = Extract data from simulation as f(location,time), write code to process data (spatial & time averages), make plots
Data analysis - Using the right tool for the job
Learning Objectives
Convert algorithm/flow charts into MATLAB code MATLAB Input/Output Logic (how we make decisions) IF/Case (the decisions) FOR and WHILE (the loops) Functions
Part 1: Input/Output
What are data input methods that you know?
• Command window
• Hard coding
• Ask for user input
What are data output methods that you know?
• No ;
• disp(x)
• fprintf
Basic MATLAB File I/O
save filename x y -ASCII • filename is the name of the file that you want to write data to.
• x, y are variables to be written to the file. ‣ If omitted, all variables are written.
• -ASCII tells Matlab to write the data in a format that you can read. ‣ If omitted, data will be written in binary format. ‣ best for large amounts of data
load filename x y • This is the complimentary command to save.
• Reads variables x and y from file filename ‣ If variables are omitted, all variables are loaded...
Saving variables to files & loading variables from files
clear;!x = linspace(-pi,pi);!y = cos(x);!save myVariables x y;! !clear;!load myVariables;!who; plot(x,y);
Formatted Output in Matlabdisp(x) - prints the contents of variable x. fprintf(...) - use for formatted printing • Allows much more control over output
• Syntax: fprintf(‘text & formatting’,variables); • Text formatting:
‣ %a.bc ‣ a - minimum width of output buffer
‣ b - number of digits past decimal point
‣ c - formatting scheme
‣ f - floating point (typical format) 12.345
‣ e - scientific notation - 1.2345e1
‣ s - string format
x = [1.1 2.2 3.3 4.4];!y = 2*x;!fprintf('Hello. (%1.3f,%1.3f), (%1.1f,%1.0f)\n',...! x(1),y(1),x(3),y(3));
Hello. (1.100,2.200), (3.3,7)
Control Code Description Example
\n Begin a new line fprintf('hello.\n');
\t Insert a “tab” fprintf('\thello.\n');
\\ insert a backslash fprintf('\\hello.\\\n');
'' Insert a single quote fprintf('''hello.''\n');
%% Insert a % sign fprintf(‘%%%1.2f\n’,95.6);
Formatted Output - Examples
fprintf('%6s%8s\n','index','value');!fprintf('--------------\n');! !n = 5;!a = zeros(5,1);!for( i=1:5 )! a(i) = 2*i+1;! fprintf('%6.0f%8.1f\n',i,a(i));!end
What does this output look like?
File Output in MATLAB
Three steps: • Open the file ‣ fid = fopen(filename,’w’);!
‣ ‘w’ tells matlab that we want to WRITE to the file.
‣ see “help fopen” for more information.
• Write to the file ‣ fprintf(fid,format,variables);
• Close the file
Example: Write code that produces a table of temperatures in F, R, C and K. User enters starting & ending temperatures (in F) & number of points in table. Write results to file called “tempTable.dat”
File Input in MATLABImport wizard “File→Import Data” • Allows you to import data from delimited files (spreadsheets, etc)
Importing “spreadsheet” data • dlmread - import data from a delimited file (you choose the delimiter) • xlsread - import data from Excel.
General file input - three steps: • fid=fopen(filename,’r’) - open a file to allow detailed input control. ‣ ‘r’ tells matlab that we want to READ from the file.
• a=fscanf(fid,format,size); ‣ Works like file writing, but use fscanf rather than fprintf. ‣ fid - file id that you want to read from ‣ format - how you want to save the information (string, number) ‣ ‘%s’ to read a string, ‘%f’ to read a floating point number, ‘%e’ to read scientific
notation. ‣ size - how many entries to read. ‣ feof(fid) - returns true if end of file, false otherwise.
• fclose(fid);
clear; clc;!!% open a file to read - first line contains!% the order of the polynomial. Second line!% contains the polynomial coefficients.!fid = fopen('poly.dat',’r’);! !% read the order of the polynomial!n = fscanf(fid,'%f',1);! !% read all of the polynomial coefficients!a = fscanf(fid,'%f',n+1);
4!1.0 2 0.02 4.0 0
2!0 1 2.3
“poly.dat”
“poly.dat”
File Input - Example
p(x) =4�
i=0
ai xi = a0 + a1x + a2x2 + a3x
3 + a4x4
p(x) =n�
i=0
ai xiGeneral form of an nth order polynomial:
For a quartic (n=4) we have:
Basic ConceptsPrograms
so farBranching
if(condition)
path if condition
is true
path if condition
is false
These basic elements can be combined to create complex program logic.
Looping
while( )!for( )
The “if” StatementBasic syntax: if ( condition1 )!% do some work!
elseif ( condition2 )!% do different work!
⋮!else!% do default work!
end
cond
ition
1
cond
ition
2
defa
ult
othe
r
cond
ition
s...
if ( condition )% do some work
end
if ( condition )% do some work
else% do default work
end
Create a MATLAB script to plot cos(x) an sin(x) on a user-specified interval. The user should be able to enter the interval in degrees or radians.
The “switch/case” StatementBasic syntax: switch switch_expression!! case case_expression!!! % do some work!
! case case_expression!!! % do different work!
⋮!! otherwise!!! % do default work!
end
case
1
case
2
defa
ult
othe
r
case
s...
Example - what is output? city=input(‘Enter the name of a city: ’,’s’)!switch city! case ‘Boston’!! disp(‘$345’)! case ‘Denver’!! disp(‘$150’)! case ‘London’!! disp(‘Arm and Leg’)! otherwise!! disp(‘Airfare not on file’)!end
Relational OperatorsTrue condition represented by a nonzero (typically “1”). False condition represented by zero “0” Can be applied to scalars, vectors, or matrices.
Statement Result Example True or False
a == b true if a and b are equal 5==3 0
a ~= b true if a and b are NOT equal 5~=3 1
a < b true if a is less than b 5<3 0
a > b true if a is greater than b 5>3 1
a >= b true if a is not less than b 5>=3 1
a <= b true if a is not greater than b 5<=3 0
Comparison Operators
Example: What does this do?dice = 3*rand(1); % a number between 0 and 3!if( dice<1 )! name = 'Bob';!elseif (dice<2)! name = 'Fred';!else! name = 'Jane';!end! !dice = 3*rand(1); % a number between 0 and 3!if dice<1! age = 25;!elseif dice<2! age=19;!else! age = 40;!end! !fprintf('\n%s is %1.0f years old\n\n',name,age);
NOx Data Analysis
NOx Data Analysis if axial_loc == 1: axial_name = '0_457m' dataFile = 'chevron_expData/chevron_1.5ft.dat' dist = '1.5_ft' elif axial_loc == 2: axial_name = '1_372m' dataFile = 'chevron_expData/chevron_4.5ft.dat' dist = '4.5_ft' elif axial_loc == 3: axial_name = '2_287m' dataFile = 'chevron_expData/chevron_7.5ft.dat' dist = '7.5_ft' else:
print('You selected an invalid option for axial location')
NOx Data Analysis Extracted data from simulation is saved in directories with the following names: 0_457m, 1_372m, 2_287m.
Write a script that uses an if/elseif structure to determine which directory to process
Now do the same thing using a switch/case structure
See http://blogs.mathworks.com/pick/2008/01/02/matlab-basics-switch-case-vs-if-elseif/
Relational OperatorsTrue condition represented by a nonzero (typically “1”). False condition represented by zero “0” Can be applied to scalars, vectors, or matrices.
Operator Description
& Element-wise AND - returns an array of 1 and 0.
| Element-wise OR - returns an array of 1 and 0
~ Element-wise NOT - returns an array of 1 and 0
Logical Operators
Function Description
any(var) returns true if any element of var is true
all(var) returns true (1) if all elements of var are true.
find(var) returns the indices where var is true (nonzero).
isequal(var1, var2) returns true (1) if the two arrays are equal.
strcmp(str1,str2) Compares two strings and returns true if they are equal.
abs(var) returns the absolute value of all elements of var.
ceil(var) rounds all elements of var up.
floor(var) rounds all elements of var down.
mod(var1,var2) Remainder of division of var1 by var2.
A Few More Useful Functions
Example - Data Analysis
Generate a set of random numbers between 1 and 100.
• What percentage of these numbers are between 40 and 60?
• How many numbers did it take to get a consistent answer?
Repeat this example to determine what percentage are between 90 and 95.
Hint: use rand & find functions.
The “for” StatementPredetermined looping
Basic syntax:
for(counter=start:step:stop)% do some work
end
increment counterby step each timeloop is executed.
Example - what are the values in a? n=10;!a = zeros(n,1);!for i=1:1:n! a(i) = 2*i;!end
The “for” StatementPredetermined looping
Basic syntax:
for(counter=start:step:stop)% do some work
end
increment counterby step each timeloop is executed.
Example - what are the values in a? n=10;!a = zeros(n,1);!for i=1:1:n! a(i) = 2*i;!end
Example - what are the values in a? n=10;!a = zeros(n,1);!for i=1:n! a(i) = 2*i;!end
The “for” StatementPredetermined looping
Basic syntax:
for(counter=start:step:stop)% do some work
end
increment counterby step each timeloop is executed.
Example - what are the values in a? n=10;!a = zeros(n,1);!for i=1:1:n! a(i) = 2*i;!end
Example - what are the values in a? n=10;!a = zeros(n,1);!for i=1:n! a(i) = 2*i;!end
Example - what are the values in a? n=10;!a = zeros(n,1);!for i=n:-1:1! a(i) = 2*i;!end
The “for” StatementPredetermined looping
Basic syntax:
for(counter=start:step:stop)% do some work
end
increment counterby step each timeloop is executed.
Example - what are the values in a? n=10;!a = zeros(n,1);!for i=1:1:n! a(i) = 2*i;!end
Example - what are the values in a? n=10;!a = zeros(n,1);!for i=1:n! a(i) = 2*i;!end
Example - what are the values in a? n=10;!a = zeros(n,1);!for i=n:-1:1! a(i) = 2*i;!end
Example - what are the values in a?!a = zeros(3,1);!for i= [1 2 5]! a(i) = 2*i;!end
The “while” StatementConditional Looping
Basic syntax:
while ( condition )% do some work - must result% in condition being changed% at some point!
end
Example - What is the value of n? a = 1;!n = 0;!while (a<10)! a = a+2;! n = n+1;!end
check conditioneach time loop is
executed.
How “while” can trip you upMost important thing about WHILE is missing from this loop; what is it?
Exit criteria is never reached because value of condition variable stops changingWhat can you do?
Ctrl+C to break the loop manuallyUse break - Statements in loop after break do not execute. If loops are nested, control
passes to statement that follows end of loop.Assign variable that acts as counter, break if counter gets too high
Example - What happens here? n = 0;!k = 1;!while n < 2! n = n + 1/k;! k = k*2;!end!n!k
How “while” can trip you upMost important thing about WHILE is missing from this loop; what is it?
Exit criteria is never reached because value of condition variable stops changingWhat can you do?
Ctrl+C to break the loop manuallyUse break - Statements in loop after break do not execute. If loops are nested, control
passes to statement that follows end of loop.Assign variable that acts as counter, break if counter gets too high
Example - What happens here? n = 0;!k = 1;!while n < 2! n = n + 1/k;! k = k*2;!end!n!k
Example - What happens here? n = 0; k = 1; count = 0; while n < 2 n = n + 1/k; k = k*2; count = count + 1; if count > 100 break end end n k count
The “break” Statement“break” exits the current loop structure.
What control structure would produce these two pictures?
condition is satisfied
Example - Compute polynomial
p(x) =4�
i=0
ai xi = a0 + a1x + a2x2 + a3x
3 + a4x4
p(x) =n�
i=0
ai xiGeneral form of an nth order polynomial:
For a quartic (n=4) we have:
Read coefficient values from file, compute f(x)
Example - Compute polynomial
p(x) =4�
i=0
ai xi = a0 + a1x + a2x2 + a3x
3 + a4x4
p(x) =n�
i=0
ai xiGeneral form of an nth order polynomial:
For a quartic (n=4) we have:
Read coefficient values from file, compute f(x)clear; clc;!!% open a file to read - first line contains!% the order of the polynomial. Second line!% contains the polynomial coefficients.!fid = fopen('poly.dat',’r’);! !% read the order of the polynomial!n = fscanf(fid,'%f',1);! !% read all of the polynomial coefficients!a = fscanf(fid,’%f',n+1);!!% add in loop to read multiple sets of coefficients from poly.dat, compute f(x) for all sets of coefficients
Example: Factorial
Write a Matlab code to calculate the factorial of a number using:
1. A for loop 2. A while loop
n! =n�
i=1
i
NOTE: MATLAB’s factorial function will do this much faster than using loops will.