0% found this document useful (0 votes)
47 views63 pages

09 18 2020 - Mathlab Intro 2

This document discusses creating 2D plots in MATLAB, including: 1. Creating a bar plot of precipitation data using the subplot function to divide the figure window into sections. 2. Adding a normal line plot of evaporation data and a marker plot on the same subplot axis. 3. Plotting streamflow data as an area plot and marker plot on another subplot. 4. Creating a semilog plot of streamflow data on the last subplot with different line styles. 5. Bringing all subplots together to show the final multi-panel figure with different hydrologic time series plots. 6. Providing a simple example of a scatter plot of precipitation versus streamflow data in

Uploaded by

Theo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views63 pages

09 18 2020 - Mathlab Intro 2

This document discusses creating 2D plots in MATLAB, including: 1. Creating a bar plot of precipitation data using the subplot function to divide the figure window into sections. 2. Adding a normal line plot of evaporation data and a marker plot on the same subplot axis. 3. Plotting streamflow data as an area plot and marker plot on another subplot. 4. Creating a semilog plot of streamflow data on the last subplot with different line styles. 5. Bringing all subplots together to show the final multi-panel figure with different hydrologic time series plots. 6. Providing a simple example of a scatter plot of precipitation versus streamflow data in

Uploaded by

Theo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

WATER RESOURCES

SYSTEMS ENGINEERING Week 3

Doosun Kang
Kyung Hee University
Water Resources Systems Engineering (Wk3) 2

2-D Plotting
Water Resources Systems Engineering (Wk3) 3

2-dimensional plot

Legend Plot title

Y axis label

Text label

Line

Marker

X axis label
Water Resources Systems Engineering (Wk3) 4

“plot” syntax Ask tips by typing “>> doc plot”

plot(x, y, ‘Line specifiers’, ‘PropertyName’, PropertyValue)

Line color Symbol Marker Symbol Line sort Symbol


Red r Plus + Solid line -
Green g Circle o Dashed line --
Blue b Star * Dotted line :
Cyan c Dot ∙ Dash-dot line -.
Magenta m Cross x
Yellow y Square s >> x = 0:0.1:pi;

>> y = sin(x);
Black k Pentagon p
>> plot(x, y, '--r∗ ′, 'linewidth', 2, 'markersize', 12)
White w Hexagon h
Water Resources Systems Engineering (Wk3) 5

2-D line plot

>> x = [1988:1:1994];

>> y = [8 12 20 22 18 24 27];
Try other
>> plot(x, y, '--r∗ ′, 'linewidth', 2, 'markersize', 12)
properties
Water Resources Systems Engineering (Wk3) 6

2-D line plot – multiple lines

>> x = [-2:0.01:4];

>> y1 = 3∗x.^3-26∗x+6;

>> y2 = 9∗x.^2-26;

>> y3 = 18∗x;

>> plot(x, y1, ʹ-bʹ , x, y2, ʹ--rʹ , x, y3, ʹ:kʹ)

x, y3 >> plot(x, y1, ʹ-bʹ); hold on


>> plot(x, y2, ʹ--rʹ);

x, y1 >> plot(x, y3, ʹ:kʹ); hold off

x,y2
Water Resources Systems Engineering (Wk3) 7

2-D line plot - exercise


>> x = [10:0.1:22];
>> y = 9500./x.^2;
>> xd = [10:2:22];
>> yd = [950 640 460 340 250 180 140];
>> plot(x, y, ʹ-ʹ, ʹLinewidthʹ, 1.0)
>> xlabel(ʹDISTANCE (cm)ʹ)
>> ylabel(ʹINTENSITY (lux)ʹ)
>> title(ʹLight Intensity as a Function of Distanceʹ, ʹFontSizeʹ,14)
>> axis([8 24 0 1200])
>> text(14,700,ʹComparison between theory and experiment.ʹ,ʹEdgeColorʹ,ʹrʹ,ʹLinewidthʹ,2)
>> hold on
>> plot(xd, yd, ʹro--ʹ, ʹlinewidthʹ, 1.0, ʹmarkersizeʹ, 10)
>> legend(ʹTheoryʹ, ʹExperimentʹ, 0)
>> hold off
Water Resources Systems Engineering (Wk3) 8

Loading Data
&
Creating Plots
Water Resources Systems Engineering (Wk3) 9
Load Leaf-River Data:
Water Resources Systems Engineering (Wk3) 10

>> clear all;


>> close all;
>> load LeafCatch.dat;

>> Period = [1:365]';


>> Precip = LeafCatch(Period,1);
>> Evap = LeafCatch(Period,2);
>> Flow = LeafCatch(Period,3);

clear all; % Clears everything from the workspace


close all; % Closes all existing figure windows
load filename; % Loads the data file into array having the same
name as the data file
Period = [a:b]’; % Creates column vector named ‘Period’ having
values from ‘a’ to ‘b’ in steps of 1
Precip = LeafCatch(Period,1); % Creates column vector named
‘Precip’ consisting of the row numbers indicated
by ‘Period’ and the column number ‘1’
Figure(1) … Subplot(4,1,1) … Bar plot … Grid on … Axis … 11
Water Resources Systems Engineering (Wk3) 11

PP (mm) Leaf River Daily Precipitation Data (WY 1948)

P as Bar Plot

figure(1); Opens the figure window number 1

subplot(4,1,1); Creates a sub-plot in the window


Syntax → subplot(nrows, ncols, plot number)
bar(Period, Precip); Creates a bar plot in the subplot area
grid on; Turns the grid on
Sets the axis limits [minX maxX minY maxY]
axis([min(Period) max(Period) 0 1.1*max(Precip)]);
axis ij; Sets the origin to top-left-corner

ylabel('PP (mm)');
title('Leaf River Daily Precipitation Data (WY 1948)');

legend('P as Bar Plot',4); Creates a legend in bottom-right-corner


Figure(1) … Subplot(4,1,2) … Normal Line plot … Hold on … 12
Water Resources Systems Engineering (Wk3) 12

PP (mm) Leaf River Daily Precipitation Data (WY 1948)

P as Bar
Plot
ET (mm)

subplot(4,1,2); Creates a new sub-plot in the window


Creates a line plot (blue line) in the subplot area
plot(Period, Evap,'b-','linewidth',1.5);
hold on; ‘Holds’ the plot for over-writing

Creates a marker plot (black dots) in the subplot area


plot(Period, Evap,'k.','markersize',10);
hold off; Turns ‘off’ the ‘hold’ feature
Figure(1) … Subplot(4,1,3) … Area plot … 13
Water Resources Systems Engineering (Wk3) 13

subplot(4,1,3);
area(Period,Flow,'edgecolor','k', …
'facecolor',0.95*[0.6 0.9 1]); hold on;
Creates an area plot (blue area) in the subplot area
plot(Period, Flow,'ko','linewidth',1.5, …
'markersize',4); hold off;
Creates a marker plot (black circles) in the subplot area
ylabel('Q (cms)');
legend('Q as o-symbol','Q as area plot',0);
Q as o-symbol
Q as area plot
Q (cms)
Q (cms)

Time (Days)
Figure(1) … Subplot(4,1,4) … Semilogy Line plot … 14
Water Resources Systems Engineering (Wk3) 14

subplot(4,1,4);
semilogy(Period, Flow,'k-',Period, Flow,'r.', …
'linewidth',1,'markersize',10);
Creates a semilog line plot (black line) in the subplot
area with a log-scale y-axis

axis([min(Period) max(Period) 0 1.1*max(Flow)]);


ylabel('Q (cms)');
xlabel('Time(days)');
legend('Q as line plot','Q as dot-markers',2);
Q (cms)

Time (Days)
Final Plot: 15
Water Resources Systems Engineering (Wk3) 15

PP (mm) Leaf River Daily Precipitation Data (WY 1948)

P as Bar
Plot
ET (mm)

Q as o-symbol
Q as area plot
Q (cms)
Q (cms)

Time (Days)
Another Simple Example - Scatterplot:
Water Resources Systems Engineering (Wk3) 16

figure(2);

plot(Precip,Flow,'b.','markersize',15);
axis('square');

xlabel('Precip (mm)');
ylabel('Flow (cms)');
title('Scatterplot Leaf River Data(WY 1948)');

legend('Data as dot-markers',0);
grid on;
Other types of Plots:
Water Resources Systems Engineering (Wk3) 17

0.9

0.8

0.7

0.6
kq

0.5

0.4

0.3

0.2

0.1

0
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
alpha

Contour plots
Mesh plots (3-D)
Surface plots (3-D)
Histograms
… etc …
Water Resources Systems Engineering (Wk3) 18

Assignment #2

1. Try to understand each line of the “LeafCatch” plots

2. Take a data set of your own choosing (but NOT the


LeafCatch.dat), load the data into Matlab, and create some
appropriate kinds of plots that help you to visualize the data.

Use the ‘demo’, ‘help’ and ‘doc’ features of Matlab to find the
kinds of plots you want, and to learn the correct syntax.

Turn in a hardcopy of the plots, along with a hardcopy of the


Matlab code used to generate the plots.
Submit plots along with Matlab code used to generate the
plots (as a single PDF file, upload in e-campus).
Water Resources Systems Engineering (Wk3) 19

Tips – Copy and paste figure files

Paste into ‘hwp’


or ‘word’ file
Water Resources Systems Engineering (Wk3) 20

MATLAB Scripts
Water Resources Systems Engineering (Wk3) 21

Creating & Editing Script Files

>> edit;

File name should begin


with letter

➢ Enter your commands


➢ Save as “ExampleScript.m”
Water Resources Systems Engineering (Wk3) 22

>> edit;

>> ExampleScript
Example – “Scatterplot.m”
Water Resources Systems Engineering (Wk3) 23

clear all;
close all;
load LeafCatch.dat;

Precip = LeafCatch(1:365, 1);


Evap = LeafCatch(1:365, 2);
Flow = LeafCatch(1:365, 3);

figure(1)
plot(Precip,Flow,'b.','markersize',15);
axis('square');

xlabel('Precip (mm)');
ylabel('Flow (cms)');
title('Scatterplot Leaf River Data(WY 1948)');

legend('Data as dot-markers',0);
grid on;
Water Resources Systems Engineering (Wk3) 24

Standardization of M-file layout

Tip: By standardizing m-file layout, you create easy-to-read m-files.


Use the following standard structure and comment line format:

%Header: describes the m-file project, author, date info.

%Initialization:
clear all, close all, clc(optional)
Loading data files if you have to

%Calculations:
Command structure for all calculations

%Output & Visualization:


Command structure for figures and graphics plots.
Water Resources Systems Engineering (Wk3) 25

M-file operation
ScriptTest1.m
% Water Resources System Engineering

game1 = 75;

game2 = 93;

game3 = 68;

ave_points = (game1 + game2 + game3)/3;

Command window

>> ScriptTest1

>> ave_points

ave_points =

78.6667
Water Resources Systems Engineering (Wk3) 26

Read & Write


in
Command window
Water Resources Systems Engineering (Wk3) 27

M-file operation – ‘input’ function


Variable_name = input(ʹUser input textʹ)

ScriptTest2.m
% Water Resources System Engineering
game1 = input(‘1st game score =’);
game2 = input(‘2nd game score =’);
game3 = input(‘3rd game score =’);
ave_points = (game1 + game2 + game3)/3;

Command window
>> ScriptTest2.m
1st game score = 67 User type-in
2nd game score = 91
3rd game score = 70
>> ave_points
ave_points =
78.6667
Water Resources Systems Engineering (Wk3) 28

M-file operation – ‘disp’ function


disp(variable_name) or disp(‘User input text')

ScriptTest3.m
% Water Resources System Engineering
game1 = input(‘1st game score =’);
game2 = input(‘2nd game score =’);
game3 = input(‘3rd game score =’);
ave_points = (game1 + game2 + game3)/3; Command window
disp(‘ ’); >> ScriptTest3

disp(‘Total average = ’); 1st game score = 89 User type-in


disp(ave_points); 2nd game score = 60

3rd game score = 82

Total average = Displayed in


77 command window
Water Resources Systems Engineering (Wk3) 29

M-file operation example

% Water Resources System Engineering

yr = [2007 2008 2009 2010 2011 2012 2013];

pop = [127 130 136 145 158 178 211];

tableYP(:,1) = yr’;
YEAR POPULATION
tableYP(:,2) = pop’;
(MILLIONS)
disp(‘ YEAR POPULATION’)
2007 127
disp(‘ (MILLIONS)’ )
2008 130
disp(‘ ’) 2009 136
disp(tableYP) 2010 145
2011 158
2012 178
2013 211
Water Resources Systems Engineering (Wk3) 30

Read & Write


in
Command window

“input” & “disp”


3
Water Resources Systems Engineering (Wk3) 1

“input” function
Variable_name = input(ʹUser input textʹ)

>> game = input(‘First game grades :’);


>> game

“disp” function
disp(‘User input text') or disp(variable_name)

>> disp(‘ === display results === ’);

>> disp([‘game score = ’, num2str(game)]);


Water Resources Systems Engineering (Wk3) 32

Read & Write


from
Text file

“load” & “fprintf”


3
Water Resources Systems Engineering (Wk3) 3

“load” function
load file_name or load('file_name')
TestData.txt

Save to “var”

Save to “TestData”
3
Water Resources Systems Engineering (Wk3) 4

“fprintf” function
1 2 3
file open Write file close
“fopen” “fprintf” “fclose”

1
fid = fopen('file_name', ‘w’) Testfprintf.m
file id 'w' = write x = 1:10;
y = [x; exp(x)];
2
fprintf(fid, ‘writing_format', value) 1 fid = fopen('exp.txt', 'w');
2 fprintf(fid, '%5i%10.2f\n', y);
format is important
3 fclose(fid);
3
fclose(fid)
3
Water Resources Systems Engineering (Wk3) 5

“fprintf” – writing format


x = 1:10;
y = [x; exp(x)];
fprintf(fid, '%5i%10.2f\n', y);
fid = fopen('exp.txt', 'w');
fprintf(fid, '%5i%10.2f\n', y); Field width \n : new line

fclose(fid); Integer

exp.txt
fprintf(fid, '%5i%10.2f\n', y);
Field width

Precision

Floating-point
number
Water Resources Systems Engineering (Wk3) 36

Read & Write


from
Excel file

“xlsread” & “xlswrite”


3
Water Resources Systems Engineering (Wk3) 7

“xlsread” function test1.xls


Variable_name = xlsread(filename, sheet, range)

>> A = xlsread(‘test1.xls’, 1, ‘A4:B5’);


>> A = 4 9
5 10

“xlswrite” function
xlswrite(filename, variable_name, sheet, range) test2.xls

>> d = {‘Time’, ‘Temp’ ; 12 98; 13 99; 14 97}


>> xlswrite(‘test2.xls’, d, ‘Temp’, ‘B2’);

Note) “xlsread / xlswrite” – not recommended since R2019a, instead try


“readtable / writetable”, “readmatrix / writematrix”, and “readcell / writecell”.
Water Resources Systems Engineering (Wk3) 38

Flow Control Functions


3
Water Resources Systems Engineering (Wk3) 9

Types of Flow Control Expressions

(1) for-end loops


(2) while-end loops
(3) if-else-end constructions
4
Water Resources Systems Engineering (Wk3) 0

for - end loops


“for-end loops” allow a group of commands to be repeated a
fixed, predetermined number of times.
The general form of a for-end loop is:
for x = vector
%assignment statements
end
For example:
>> for i = 1 : 5
>> b1(i) = i^2;
>> end
The above gives the same result as:
>> b2(1:5)=[1:5].^2;
It is up to you what you find easier.
PROS → “for-end loops” can be easier to understand.
CONS → MATLAB calculations are faster without loops.
4
Water Resources Systems Engineering (Wk3) 1

for - end loops

clear all
tic; clear all
for i=1:100000 tic;
b1(i)=i^2; vs. b2(1:100000)=[1:100000].^2;
end time2=toc;
time1=toc;

➔ Same results
but, computation times are very different
4
Water Resources Systems Engineering (Wk3) 2

for - end loops

for i = First : Last


b(i) = i^2
end

i = First
i = i + 1
b(i) = i^2

end Y i == Last ? N
Water Resources Systems Engineering (Wk3) 43

while - end loops


“while-end loops” allow a group of commands to be repeated
while a condition is true
The general form of a while-end loop is:
while condition_is_true
%assignment statements
end
Example:
Value = 0; While_End.m
step = 0;
Max = 200;
while Value < Max
Value = Value + rand;
step = step + 1;
end
disp([‘Max reached. Steps = ' num2str(step)])
Water Resources Systems Engineering (Wk3) 44

while - end loops


Value = 0;
step = 0;
Max = 200;
while Value < Max Value = 0
Value = Value + rand step = 0
step = step + 1 Max = 200
end

end N Value < Max ?


Y

Value = Value + rand


step = step + 1
Water Resources Systems Engineering (Wk3) 45

if – else – end constructions

“if-else-end” constructions allow a group of commands to be


conditionally evaluated based on a relational test.

The general form of an if-else-end construction is:


if expression_is_true
%assignment statements
else
% assignment statements
end
Water Resources Systems Engineering (Wk3) 46

if – else – end constructions

if expression1
% run if expression1 is True otherwise skip
elseif expression2
% run if expression2 is True otherwise skip
elseif expression3
% run if expression3 is True otherwise skip
elseif expression4
% run if expression4 is True otherwise skip
else
% run if none of the above expressions is True
end
Water Resources Systems Engineering (Wk3) 47

if – else – end constructions


friction = 20
friction = 20; T1 = 25
T1 = 25; T2 = 15
T2 = 15;
if friction > T1
A = 3; N friction > T1 ? Y

elseif friction > T2


A = 2; end A=3
else;
A = 1;
end
N friction > T2 ? Y

end A=2

A=1 end
Water Resources Systems Engineering (Wk3) 48

Flow Control Exercises


Water Resources Systems Engineering (Wk3) 49

Flow Control Exercise

x(1)=3; MATLAB returns:


for n = 2:6 x = [3 6 12 24 48 96]
x(n) = 2 * x(n - 1);
end

n=1; MATLAB returns:


while prod(1:n) < 100 result = 4
n = n + 1;
end
result = n - 1;

for i=1:10 MATLAB returns:


a = 2*i; ID = [0 0 0 0 0 0 0 0 0 0]
if rem(a,2)==0
ID(i)=0;
else
ID(i)=1;
end
end
Water Resources Systems Engineering (Wk3) 50

Function M-files
5
Water Resources Systems Engineering (Wk3) 1

Uses of “function” files

x=2

Input value

Function

Output result y = f(x) = 2*x

y=4
5
Water Resources Systems Engineering (Wk3) 2

“function” m-file syntax

(input variables) function(.) [output variables]

function [output variables]=function_name(input variables)

function m-file
a) the very first word is "function"
b) defines the function name
c) lists the inputs to the function
d) lists the outputs created by the function

The word "function“ appearing in the function definition line, must always
be typed in lower case.
5
Water Resources Systems Engineering (Wk3) 3

“function” m-file syntax

O1
I1
calc(.) O2
I2 O3

Example of first line of function file called “calc.m”

function [O1, O2, O3] = calc(I1, I2)

calc → name of function


I1, I2 → inputs to the function
O1, O2, O3 → outputs from the function
5
Water Resources Systems Engineering (Wk3) 4

“function” m-file syntax

[output variables]=function_name(input variables)

Outputs within Inputs within


square brackets round brackets

[O1, O2, O3] = calc(I1, I2)

Notes:
a) The orders of the input and output variables are
important
5
Water Resources Systems Engineering (Wk3) 5

“function” example

% Script File Main.m


function [Y1,Y2,Y3]=calc(X1,X2)
% Initialization Section
%% Function File Calc.m
I1 = [1:1:10];
I2 = 2;
% Computation Section
Y1 = X1’*X1;
% Computation Section
Y2 = X2*X1;
[O1,O2,O3] = calc(I1,I2);
Y3 = X2+5;
P1 = O1(1,:);
P2 = O3+1;
[Q1,Q2] = calc(P1,P2);
calc.m
M1 = calc(Q2,O3);

Main.m
5
Water Resources Systems Engineering (Wk3) 6

Program structures
main f1 f2

f3 f1 f2

f2

f1 f2
5
Water Resources Systems Engineering (Wk3) 7

Program structures w/ and w/o function file


% Main.m % Main.m func.m
% 1st calculation % 1st calculation

call func.m

% 2nd calculation

call func.m
% 2nd calculation
VS % 3rd calculation

call func.m

disp (‘End of Main.m’)

% 3rd calculation

disp (‘End of Main.m’)


5
Water Resources Systems Engineering (Wk3) 8

Advantages of using “function”

1. The use of function m-files helps to organize the


program.

2. A function m-file can be called many times within a


program. So, the commands for similar calculations
need only be written once, in a function m-file.
Water Resources Systems Engineering (Wk3) 59

“function” Exercises
Water Resources Systems Engineering (Wk3) 60

“function” exercise
stat.m
function [stat1,stat2,stat3] = stat(x)
stat1 = length(x);
stat2 = sum(x)/stat1;
S = sort(x);
stat3 = S(1);

>> a = [0 -1 2 3 -4];
>> [S1,S2,S3] = stat(a)
MATLAB returns: S1 = 5
S2 = 0
S3 = -4
Water Resources Systems Engineering (Wk3) 61

“function” exercise
mean_st.m
function [mean,stdv] = mean_st(x)
n = length(x);
mean = sum(x)/n;
stdv = sqrt(sum(x.^2)/n – mean.^2);

>> a = [1:10];
>> [m,s] = mean_st(a)

MATLAB returns: m = 5.5


s = 2.87228
Water Resources Systems Engineering (Wk3) 62

Types of errors
Water Resources Systems Engineering (Wk3) 63

Types of errors

Syntax errors:
▪ Misspelled variables or function names
▪ Missing quotes or parentheses
▪ Errors are found and displayed in command window when
MATLAB evaluates an expression
▪ MATLAB flags these errors immediately and provides
feedback about
▪ the type of error encountered
▪ the line number in the m-file where it occurs.
▪ Given this feedback, such errors are usually easy to spot.

You might also like