Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

14.

1 Course Example - Comparing Prices: (1/2) Comparing Gasoline Prices

The matrix prices  contains the


average annual gasoline prices
where the columns represent the
countries and the rows represent
the years 1990 through 2008

How can you allow the user to


enter the name of a country and
then have your program plot the
prices for the given country?

To do this, your program will need


to make decisions based on the
user's input, such as warning the
user about invalid input.
For valid input, your program will
need to perform its analysis,
repeating similar commands for
each country in the data set.

Keywords are reserved words Iskeyword


with special meanings.
Cho ra khoảng 20 keyword cho lập trình.
TASK
To see a list of MATLAB
programming keywords, type:

iskeyword

14.2 User Interaction: (1/8)

Introduction
Introduction: User
Interaction Similarly, you can communicate the state of the program back to the user. For
One way to get the user's input is example, if the user enters a country which doesn't exist in the data set, you can
to explicitly ask the user to type display a custom error message. 
one of the possible values. 
The data is not available for the country entered.

You can gather information from the user using the inputdlg function.

Try entering the following command in the script.


ctry = inputdlg('Enter a country')
A cell array named ctry which contains the characters the user types into the dialog
is saved in the workspace.

14.2 User Interaction: (3/8) Display Output


You can use the disp function to display information to the user. Enclose the disp('I love you honey')
message in single quotes.

disp('Message to the user')


Message to the user
TASK
Use the disp function to display any message you like.

The warning function will show the user the warning message you specify. warning('missing data')
warning('This is a warning!')
Warning: This is a warning!

TASK
Create a warning message with the text missing data.

The error function will show the user the error message you specify. error('bad data')
error('This is an error!')
This is an error!

TASK
Create an error message with the text bad data.

You can create dialog boxes that display messages, errors, or warnings. The corresponding functions
are msgbox, errordlg, and warndlg.
msgbox('Analysis complete')
errordlg('Data not found')
warndlg('Non-integer values rounded.')
Try making each of these dialog boxes.

Please close any open dialog boxes by clicking OK before moving on.

When you are finished practicing, please move to the next section.
14.3 Decision Branching: (1/10) Introduction
You can create a program that will respond to a user's input,
taking different actions based on that input. 

This is known as decision branching and allows you to control


which commands get executed in your program based on a
condition. Here we will discuss two methods for decision
branching: the if-elseif-else construction and the switch-
caseconstruction. 

Each if statement must be followed by a condition that


evaluates to true or false. The code between
the ifand end keywords is executed only when the
condition is true.

x = rand;
if x > 0.5
y = 3; % Executed only if x > 0.5
end
TASK
Modify the script so that the variable B is defined as 1
only when A is greater than 1.
if A > 1
B=1
end
You may want to execute some other code if the condition TASK
is not met. To do this, you can use the else keyword. Try modifying the script so that when the if condition is
x = rand; not satisfied, the script will set the variable B to 0.
if x > 0.5
y = 3; if A > 1
else
y = 4;
B=1 ;
end else
B=0
end
14.3 Decision Branching: (6/10) Using if-elseif-else
TASK if income < 9275
Modify the script so that when income < 9275, the value rate =0.1
of rate = 0.10. Otherwise, rate = 0.15. else
rate = 0.15
end
If the condition after the if statement evaluates to false, TASK
you can use elseif to check another condition. Further modify the script so that:
Multiple elseif blocks may be added. If they all evaluate
to false, then the else block is evaluated.  When income < 9275 ⇒ rate = 0.10

if condition  When 9275 <= income < 37650 ⇒ rate =0.
code 15
elseif condition1
code  When income >= 37650 ⇒ rate = 0.25
elseif condition2
code if income < 9275
else
code rate = 0.10
end elseif 9275<= income & income < 37650
rate = 0.15
else rate = 0.25
end

TASK IF INCOME < 9275


Further modify the script so that: RATE = 0.10
ELSEIF 9275<= INCOME & INCOME < 37650
RATE = 0.15
 When income < 9275 ⇒ rate = 0.10 ELSEIF INCOME>=37650 & INCOME <91150
 When 9275 <= income < 37650 ⇒ rate =0.1 RATE = 0.25
ELSE RATE = 0.28
5 END
 When 37650 <= income < 91150 ⇒ rate =0.
25
 When income >= 91150 ⇒ rate = 0.28

14.3 Decision Branching: (7/10) Plotting Gasoline Prices


You can run the script and see that the Australian gas IF ANY(ISNAN(CTRYPRICES))
prices are plotted. However, there is a missing value, NaN, WARNING(['MISSING VALUES IN ',CTRY,' PRICE
in the prices. It would be good to issue a warning message DATA'])
to the user if there is any missing data in the plot. END
TASK
Check if there are any missing values (NaN values) in the IF ANY(ISNAN(CTRYPRICES))
country's gas prices, ctryPrices. If there are, use the WARNING(['MISSING VALUES IN ',CTRY,' PRICE
following code to issue a warning message. DATA'])
END
warning(['Missing values in ',...
ctry,' price data'])

The switch-case Construction


If there is a finite set of discrete possible values for a variable (e.g., a set of menu options or the number of dimensions
of an array), you can use the switch-case construction in place of an if-elseif-else construction.

Where there are a finite number of discrete TASK


possibilities, you can use the switch-case  Modify the script so that:
construction.  when dayNum is 1 or 7 ⇒ dayName is 'Weekend'
switch x
case 1  when dayNum is 2 ⇒ dayName is 'Monday'
disp('x is 1')
 when dayNum is 3 ⇒ dayName is 'Tuesday'
case 2
disp('x is 2')  when dayNum is 4 ⇒ dayName is 'Wednesday'
otherwise
 when dayNum is 5 ⇒ dayName is 'Thursday'
disp('x is neither 1 nor 2')
end  when dayNum is 6 ⇒ dayName is 'Friday'

switch dayNum
case 2
dayName = 'Monday';
case 3
dayName = 'Tuesday';
case 4
dayName = 'Wednesday';
case 5
dayName = 'Thursday';
case 6
dayName = 'Friday';
otherwise
dayName = 'Weekend';
end
disp(dayName)
14.4 Determining Size: (1/7) Introduction
Introduction: Determining Size
When writing MATLAB code, it is important to be able to
determine the dimensions of arrays programmatically, rather
than by looking at their size in the workspace. 

You could imagine a scenario where the data


contains n columns, and later one more column is added. If you
hard-coded n into your for-loop, e.g.for idx = 1:n, then that
last column would not get processed in the for-loop with the
modified data.

You will learn about functions size, length, and numel and


when to use each one.

14.4 Determining Size: (2/7) Using size and numel


The size function can be applied to an array to produce a single TASK
output variable containing the array size.  Try creating a variable named s containing the size
of prices.
sy = size(Year)
sy = s = size(prices)
19 1
The size function can be applied to a matrix to produce either a TASK
single output variable or two output variables. Use square Try creating variables named m and n which
brackets, [ ], to obtain more than one output. respectively contain the number of rows and
columns of the variable prices.
[yRow,yCol] = size(Year)
yRow = [m,n]=size(prices)
19
yCol =
1
If you just want to return the size of a particular dimension, TASK
specify the dimension in the call to size. Create a variable named nRows containing the
number of rows in prices.
yRow = size(Year,1) NROWS = SIZE(PRICES,1)
yRow =
19
yCol = size(Year,2)
yCol =
1
TASK NCOLS = SIZE(PRICES,2)
Create a variable named nCols containing the number of
columns in prices.

You can use the  TASK


numel Create a variable named N containing the number
 function to return the total number of elements in an array. of elements in prices.
Tot = numel(Year)
nTot = Tập đoàn tài chính cao thì phải làm gì?
19
N = NUMEL(PRICES)
14.4 DETERMINING SIZE: (3/7) USING LENGTH
he length function is often used to find TASK
the length of a vector. It works on both Try creating a variable named len containing the length of Year.
column and row vectors. However, if
applied to a matrix, the largest sized len = length(Year)
dimension is returned. 

x = ones(13,1);
lx = length(x)
lx =
13
y = ones(1,21);
ly = length(y)
ly =
21
TASK LC = LENGTH(COUNTRIES)
Try creating a variable
named lc containing the length
of countries.

14.4 Determining Size: (6/7) Determining Size


TASK NCOLS = SIZE(PRICES,2)
Save the number of columns
in prices to a variable named nCols.

Save the number of values in Year to NYRS = LENGTH(YEAR)


a variable named nYrs.
14.5 For Loops: (1/9) Introduction
Introduction: For Loops
Suppose you want to analyze the relationship between the
gasoline prices of a selected country and the gasoline prices of
all the countries in the list. How could you do this? 

One option is to find the best fit line between each set of
countries.
Rather than typing out similar commands over and over, you
can use a for-loop to execute a block of code repeatedly.

14.5 For Loops: (6/9) Looping Through a Vector


TASK for idx = 1:4
Create a for-loop that displays
the first four elements of x.
disp(x(idx))
Name the loop variable idx.
end
TASK for idx = 1:2:5
Modify the range of the loop
variable idx to start at 1, end
dis
at 5, and increment by 2.

14.5 For Loops: (7/9) Finding the Fibonacci Sequence


TASK fib(k) = fib(k-1) + fib(k-2);
Modify the script to create the
Fibonacci Sequence. Create a
loop around the given formula for k = 3:n
with an indexing variable, k, that fib(k) = fib(k-1) + fib(k-2);
begins at 3 and ends at n. end

14.5 For Loops: (8/9) Plotting Gasoline Prices for Each Country
TASK load gPrices
Currently, the script finds the
ctry = 'Japan';
linear fit between prices in Japan
and Canada.  % Find the index value for ctry
idx = strcmp(ctry,countries);
Modify the code so that linear fits ctryPrices = prices(:,idx);
are found between Japan and all
the countries in countries.
for k = 1:length(countries)
c(k,:) = polyfit(ctryPrices,prices(:,k),1)
end

linfit = ctryPrices.*c(:,1)' + c(:,2)';


plot(ctryPrices,linfit)
legend(countries,'Location','eastoutside')
xlabel([ctry,' price'])
ylabel('Country price')

Summary: For Loops

14.6 While Loops: (1/11) Introduction


While Loops
To use a for-loop, you need to know in advance how

many iterations are required. If you want to execute a


block of code repeatedly until a result is achieved, you
can use a while-loop.

For the gasoline prices application, you may wish to


ask the user for the name of a country, and if it doesn't
exist, ask for another name until a name in the list is
provided. This can be done using a while-loop. 
14.6 While Loops: (3/11) The while-Loop Construction
A while-loop has the structure shown. 
while condition
The code statements 1, 2, 3, etc. are executed statement 1
while condition evaluates to true. statement 2
Suppose you want to find n statement 3
n …
 such that x/2 end
n
 is less than 1. You can write a while-loop and divide x by 2
 in the body of the loop as long as the result is greater than 1. 
nitialize the value of  n  to 0. Also,
create a variable  r to store the
intermediate computations, and
0
initialize  r to be  x/2 , i.e.,  x
At the loop, the condition  x/
(2^n)  > 1 is calculated.

Since the condition is true, the


body of the loop is executed. The
value of  r changes and n is
incremented by 1.
The condition is evaluated again
with the updated value of r.

The condition is evaluated again


with the updated value of r.
The condition is true, and the
body of the loop is executed
again.

The condition is true, and the


body of the loop is executed
again.
This continues until  n  is 6. At
this point, the condition evaluates
to  false and the loop execution
is complete.
14.6 While Loops: (4/11) Infinite Loops
A common problem when writing
code with while-loops is the
creation of infinite loops. This
usually happens if the variables
involved in condition are not
updated in
the statements block.
However, even if they are
updated, it is possible
that condition will never
evaluate as false. 

14.6 While Loops: (6/11) Using a While Loop


TASK while x >0.1
Modify the script so that the following code continues to
disp(x)
execute until x <= 0.1.
disp(x) x = createVar;
x = createVar;
end
What is the biggest value of epsilon such while y~=x
that 1 +epsilon is equal to 1? epsilon = epsilon/2;
TASK
Modify the script so that epsilon keeps dividing in half until
y = x+epsilon;
it is imperceptible when added to 1. end
This code reports the result.
fprintf('%4.2f + %9.3g is the same as
%4.2f',x,epsilon,x)
14.6 While Loops: (8/11) Plotting Gasoline Prices
Modify the code so that it Further Practice
allows you to enter another
Loop until success
country name if the country
you entered cannot be found
on the list.  ctry = inputdlg('Enter a country.');
ctry = ctry{1};
You may find it beneficial to
initialize idx. % Find the index value for ctry
idx = strcmp(ctry,countries);
To see an example solution
in the Editor, type the Extract data for the chosen country
following line.
ctryPrices = prices(:,idx);
edit plotGasPricesSoln Check for any missing data
if any(isnan(ctryPrices))
warning(['Missing values in ',ctry,' price data'])
When you are finished,
end
please move on to the next
section. Make plot
plot(Year,ctryPrices,'o-')
xlabel('Year')
ylabel([ctry,' Gas Prices'])
Summary: While Loops

14.7 Project - Programming Constructs: (1/2) Population Data Exercise


TASK This code creates the number of states.
Australia has 6 states.
nStates = randi(6)
Write code within the
script body to generate This code creates data based on the number of states supplied.
a warning message [Dates,netChange,stateNames] = generateData(nStates);
with the Whos
text 'Incomplete
Data' if the number of if nStates < 6
states, nStates is warning('Incomplete Data');
less than 6. end
TASK plot(Dates,netChange)
Each column
legend(stateNames)
in netChange corresponds to a
state in Australia. Plot each
column
of netChange against Dates on
the x-axis.

14.7 Project - Programming Constructs: (2/2) Following a Flight


The file flightData.mat contains information about a This code loads the flight data.
commercial flight from Los Angeles International Airport (airport
load flightData
code LAX) to Boston Logan International Airport (BOS) on July
27, 2009. The plane took off from LAX at 11:11 p.m. Pajcific This code plots the flight altitude.
Daylight Time. A plot of the aircraft's altitude vs. time is shown plot(t,altitude,'k.-')
in the script. title('Altitude of a Flight from L.A. to Boston')
The file also contains information about which air traffic control
xlabel('Time (minutes after takeoff)')
tower the flight was in contact with at what times. ylabel('Altitude (feet above sea level)')
 city contains the airport code for the tower the flight
was in contact with, and
 centers contains the times when the flight transitioned
from contact with one tower to contact with another.
For example, the first value in centers is t = 46, the time when
the flight transitioned between the first two elements of city,
Los Angeles (LAX) and Denver (DEN). The last value
of centers is NaN, since the flight never 

TASK for k = 1:length(centers)-1


Use the xline function to add blue vertical lines to the plot at the
xline(centers(k),'b');
times in the variable centers.
end
xline does not accept empty values (NaNs), so do not plot the
last element of centers. Use a semicolon after calling
the xline function to suppress its output.

You might also like