E5 MATLAB Assignment 2

The goals of this assignment are manifold. After completing the assignment you should be able to use MATLAB to

• store and access information stored in vectors,
• create number sequences,
• perform simple numerical manipulations on vectors and make simple plots,
• access elements of a vector,
• save data to, and load data from the computer's files system,
• input data from the user,

This exercise just scratches the surface of what is available in MATLAB - feel free to explore more on your own or ask Professor Cheever or one of the Wizards.

As you go through this document, you should enter the commands at the MATLAB prompt, and try variations on the commands to make sure that you fully understand.

You may want to refer to chapters 1, 2 and 5 of your text.

Vectors

(§2.1 in your text - relevant textbook sections will be bold purple text) In the previous MATLAB assignment you learned to store individual numbers in variables; these individual numbers are called "scalars."  For example

>> x=3
x =
3

(Note: you can cut the code from this document and past it directly into MATLAB; MATLAB will ignore any prompt characters, ">>" that are pasted.

However, it is often useful to be able to refer to many numbers at once.  To start, store the high temperature of each day in a week (call Sunday the first day) in a "vector" that stores several numbers in a single variable by placing successive numbers between square brackets, "[" and "]".   This is shown below (in all examples in this document MATLAB commands that you enter will be shown in green and with a Courier font, output from MATLAB will have a gray background).

>> temps=[72 78 85 82 78 70 65]
temps =
72    78    85    82    78    70    65

This is referred to as a "row" vector, because all of the numbers are in one row.  To find the temperature on Monday (the second day of the week) use an "index" to pull out the correct number.  Note: the plural of index is indices.

>> mondayTemp = temps(2)
mondayTemp =
78

To find the maximum temperature, use the "max" function

>> maxTemp = max(temps)
maxTemp =
85

Similarly find the average (or "mean") temperature

>> avgTemp = mean(temps)
avgTemp =
75.7143

It is also possible to convert all of these temperatures from Fahrenheit to Celsius with a single calculation.  Recall   Where Tc and Tf are, respectively, the Celsius and Fahrenheit temperatures.

>> tempC = (temps - 32) * 5/9
tempC =
22.2222   25.5556   29.4444   27.7778   25.5556   21.1111   18.3333

Creating Numerical Series

(§2.1)

MATLAB has a few ways to create series of numbers.  The statement "x0:xinc:xf" creates a vector starting at x0, incrementing by xi and finishing at x0.  For example to create a vector (called "days") consisting of a series if numbers starting at 1, incrementing by 1, and ending at 7 you can write

>> days=1:1:7

days =
1 2 3 4 5 6 7

The colon operator generally has three operators.  By starting at one and making the increment equal to two we can generate only odd values.

>> d=1:2:7
d =
1     3     5     7

If we don't include the increment, it defaults to one.

>> d=1:7
d =
1     2     3     4     5     6     7

Another way to create a series of numbers is with a command "linspace(x0,xf,num)."  The three arguments are the initial value "x0", the final value "xf" and the number of points "num."  To create the sequence from 1 to 7, as before

>> d = linspace(1,7,7)
d =
1     2     3     4     5     6     7

Simple Plotting

(§5.1)

To create a plot of days versus temperature, use the plot command (note: "plot(x,y)" plots the elements of the vector "x" versus those in vector "y"):

>> plot(d,temps)

This creates a plot similar to that shown (note, the first plot during a MATLAB session may take a few seconds to appear; subsequent plots appear more quickly).

This plot is rather sparse.  You can easily add a label on the x and y axes, as well as a title, to make the graph more readable as shown below.  Note that all of the text is contained within single quotes (the apostrophe (') key, on the same key as the normal double quote (")).

>> xlabel('Days')
>> ylabel('Temp, Fahrenheit')
>> title('Daily temperature over the course of a week')

It is possible to change the formatting of the plot using what MATLAB calls "LineSpec" or "Line Specification."  The line specification follows the "x" and "y" parameters in the "plot" command.  It consists of three sets of characters, a "Line Style," a "Marker" and a "Color".  Line styles include a solid line "-", a dashed line "--" (and others). Markers include a circle ("o"), a cross "x" (and others).  Colors include blue "b", red "g", black "k."  Enter "doc LineSpec" at the command prompt for more information.  To change the plot to have a dashed black line with circles at the plotted points use

>> plot(days,temps,'ko--')

Do this: Make a plot of the Celcius temperature with a magenta dotted line and diamonds.

To plot a sine function for two periods we first define a sequence of 500 numbers from zero to 4π (call this variable "theta") and then take the sine of the numbers ("y").  We then plot.

>> theta = linspace(0,4*pi,500);  % Note semicolon at end - this suppresses display of result.
>> y = sin(theta);
>> plot(theta,y); xlabel('\theta'); ylabel('y=sin(\theta)');  title('Two periods of sine function');

Note the use of the semicolon, ";" several times in this example.  The use of a semicolon after the definition of the "theta" variable in the first line suppressed the display of the result (displaying all 500 values of "theta" would fill the screen several times over).  Enter the following command (without a semicolon)

>> theta=linspace(0,4*pi,500)

Similarly in the second line (>> y = sin(theta);) would display a long sequence of numbers.   Not only does the semicolon suppress output, but it also signifies the end of a MATLAB statement.  So, in the last line there are actually four MATLAB statements, each separated from the others by a semicolon.  Note also that making using the command "xlabel('\theta')" that the Greek letter θ was used in the graph.  (Note: If you are interested you can find more information on using Greek characters (and equations) in the MATLAB documentation.)

We can add even more embellishment to the graph.  We can set the axis limits with the axis command (the four arguments are, in order, minimum x value, maximum x value, minimum y value and maximum y value).  We can also add a grid.

>> axis([0 4*pi -1.1 1.1])   % Set axis limits.
>> grid on  % Display a grid.

The "plot" command is very powerful.  You should check the MATLAB documentation (either follow link at left or enter ">> doc plot" at the command prompt).

Multiple functions on the same graph

If you try to plot a second function on a given set of axes you can see there is a problem.  Execute the following three lines one after the other (cut and paste each line into the MATLAB command window).

>> t = linspace(0,4*pi,500); x = cos(t); y = sin(t);  % Create vectors
>> plot(t,x)     % Plot variable "x"
>> plot(t,y)     % Plot variable "y".  Note this erases previous plot

Notice that when you execute the second plot command, the first plot disappears.  This problem can be solved in two ways:

Plot multiple function simultaneously

If you give the plot function several pairs of vectors to plot, it will do so on the same set of axes, making each plot in a different color.

>> t = linspace(0,4*pi,500);   x = cos(t);   y = sin(t); % Create vectors
>> plot(t,x,t,y)   % Plot variables "x" and "y" simultaneously

To distinguish one plot from the other use the "legend" command.  The arguments to the legend command correspond, in order, to vectors in the plot command.

>> legend('x=cosine(t)','y=sine(t)')   % Add a legend to the graph.

You can even apply line styles to the plots of individual vectors.

>> plot(t,x,'r:',t,y,'g-.')           % Plot vectors with specified line styles.
>> legend('x=cosine(t)','y=sine(t)')  % Add a legend.

Plot multiple functions with the "hold" command

MATLAB also has a command that disables the automatic erasing of plots.  If a plot is displayed and the command "hold on" is executed, then new plots do not erase the old one.

>> t = linspace(0,4*pi,500); x = cos(t); y = sin(t); % Create vectors
>> plot(t,x,'r');			% Plot variable "x"
>> hold on				% "hold on", so graph isn't erased
>> plot(t,y,'b:')			% Plot variable "y"
>> legend('x=cosine(t)','y=sine(t)')	% Add legend
>> hold off				% "hold off", so graph is erased with next "plot" command

You can erase the plot (and start with a clean set of axes) by either issuing a hold off command or by closing the figure window.  Keep in mind that a very common mistake is not to issue a "hold off" command so that the same set of axes is continuously reused.  You can avoid this be either closing all of the figures at the beginning of a script with a "close all" command, or by executing a "hold off" command at the beginning (the command works even if no plot has yet been created).

Accessing parts of a vector

To access parts of a vector you can use the colon operator as the index of the vector.  Start again with the vectors from the beginning of the lab:

>> d=1:7; temps=[72 78 85 82 78 70 65];

To get the weekday temperatures we want elements two through six (i.e., Monday through Friday).  You can do this by explicitly specifying each day:

>> weekdayTemps = temps([2 3 4 5 6])
weekdayTemps =
78    85    82    78    70

or by using colon notation.

>> weekdayTemps = temps(2:6)
weekdayTemps =
78    85    82    78    70

Likewise to get the temperature on Monday, Wednesday and Friday you could type:

>> MWF_Temps=temps(2:2:6)
MWF_Temps =
78    82    70

Do this: Generate variables "y" and "theta" using the code below,

>> theta = linspace(0,4*pi,500);   y = sin(theta);

and then plot the values with an index between 125 and 375. The graph should look like the one below:

User input

(§1.4)

Often it is desirable to write a script that allows the user to set parameters that affect the calculations performed by MATLAB.  Open a new script by either:

• selecting "" from the menu at the top of the MATLAB window,
• hitting the "New Script" button () at the top of the MATLAB window,
• or typing "Ctrl-N" at the MATLAB prompt.

Copy and paste the following into the document you just created (text is also in file addNums.m):

% Prompt user for two numbers and then add them

x = input('Enter first number: ');  % Get first number
y = input('Ender second number: '); % Get second number
disp('Sum of numbers');
sum=x+y                             % Calculate and display sum

Now run the code (either hit the "F5" key on the keyboard or go to "" from the menu at the top of the editor window.  A prompt occurs in the MATLAB command window asking you for the first number.  After you enter the first number it is in the variable "x".  Then do the same for the second number, "y".  The code then adds them numbers and displays the result.  To add the numbers three and four, the MATLAB command window would display the following (where user input is shown as maroon):

>>
Enter first number: 3
Ender second number: 4
Sum of numbers
sum =
7
>> 

Do this: Create a new script with the following text (also in the file plotSine.m).

% Generate a sine wave and then plot just a portion of it

theta = linspace(0,4*pi,500);       % angle
y = sin(theta);                     % sine of angle

% Add code here to prompt user for u
% upper and lower limit on plot
lower = xxxxxxxxx;
upper = xxxxxxxxx;

% Make plot using upper and lower limits
xxxxxxxxx;


Replace the text marked "xxxxxxxxx" with appropriate MATLAB commands (note: this may require more than one line).  Run the code and ensure it behaves as expected.

Important Note: When publishing a MATLAB script to a Word document the "input" function doesn't work because the command prompt cannot be used.  Instead we use the "p_input" function which opens a window.  It behaves like the "input" function but opens a small dialog box rather than using the MATLAB command prompt.  However, the "p_input" command only works in Hicks - though I can tell you how to access it from outside of Hicks if you want to do so.

Do this: Copy and paste the following into a script (text is also in file addNums2.m) - note that this is the same as before with "input" replaced by "p_input".

% Prompt user for two numbers and then add them

x = p_input('Enter first number: ');  % Get first number
y = p_input('Ender second number: '); % Get second number
disp('Sum of numbers');
sum=x+y                             % Calculate and display sum

Now run the code.  Note that you get two dialog boxes (one for "x" and one for "y").  If you examine the MATLAB command window after the code is run, the command window should look the same as if the "input" function had been used.

Saving data to a file and reading data from a file

(§1.3)

To save variables you have created in MATLAB use the "save" command.  The proper syntax for this command is:

>> save fName var1 var2 var3 ... varN

where "fName" is the name of the file to be stored and "var1", "var2", ... "varN" are the variable names.  For example if you enter the following code at the command prompt

>> theta = linspace(0,4*pi,500); y = sin(theta);
>> save myVars theta y

a file named "myVars.mat" is created in the current directory (this should be the leftmost pane of the MATLAB window) that stores the variables "y" and "theta".

Now we can delete all variables with the "clear all" command.

>> clear all

To retrieve the variables stored in a file, use the "load" command.  In this case only the filename is needed, the variable names are not necessary.

>> load myVars

To do

Dowload the files "E5M2.m" and "FebKWH.mat" to your MATLAB directory.  The data in  "FebKWH.mat" is a record of the electrical energy use at the college for a week in February.  The data was recorded by the college's electrical utility for each half hour interval throughout the week.  The units of the data are kiloWatt-hours, a unit of electrical energy.  If you execute

>> load FebKWH

the data is read into a vector "kwh" that is 336 elements long (this corresponds to 48 half hour intervals per day, starting at midnight, for 7 days).  The file "E5M2.m" is the shell of a script.  Wherever you see an "xxxx" in the code, you must add appropriate MATLAB code (perhaps several lines).  Don't forget to comment your code as necessary - your grade depends partly on the quality of your comments.  There are some comments in the code, but not nearly enough for good programming practice.  In particular there should be a block of comments at the top of the file describing what it does.  Each cell (Recall that a "cell" within  the script starts at one line that begins with "%%" and extends to the next line that begins with "%%") should also have comments within it.

If you have programming experience

If you've programmed before you might be tempted to use "if...then..else" constructs or other techniques to solve this problem.  Feel free to do so, but you are on your own in terms of learning the proper syntax... (we'll cover this later in the semester).   However, do not use any loops in your solution; one of the goals of programming in MATLAB is to use as few loops as possible, and this task requires none.

1. Split the original vector up into 7 shorter vectors, one for each day of the week.  Call these "d1" through "d7", since you don't know which day is Monday.
2. Calculate and display the average energy usage for each day.  Note that two days (the weekend) should have lower energy than the others.
3. Have the user select two days from the list: the days with the highest and the lowest energy use.  The user will identify the days with the highest and lowest use from the output of the previous step.  In this step you should use the "input" (or "p_input") function to select the two appropriate days.
4. Next create vectors with data from the two chosen days.
Hint: the day of the week with the lowest power is given to the program by the user. How can you use this information to extract the appropriate data from the original vector? Or.. if you want the data for day 3, what values would you use for the indices (indices is plural of index) into the array?  What algorithm, or calculation, did you use to figure out your response?
5. Plot the data chosen by the user on a single set of axes.  The vertical axis should have units of kiloWatt-hours, and the horizontal axis should be hours from midnight .  The graph should have axis labels, a title and a legend.  It should look like the one below (you could move the legend so it doesn't obscure the data (the "legend" command has an optional arguments that determines the placement of the legend), and change the range of the horizontal axis from 0 to 23.5; but these are not necessary).

Note that:
• Energy use is lowest in the early morning.
• Energy use stays low until almost 10:00 a.m. on the lowest day (in red; which happens to be on a weekend).  Energy use increases, unsurprisingly, much earlier on a weekday.
• Energy use peaks at about 18:00 hours = 6:00 p.m. on weekdays and drops rapidly as midnight approaches.
• Energy use drops off much more slowly on a weekend night.
6. Make sure your code has sufficient comments.  Much of your grade will depend on the clarity of these comments.  In particular, add a section at the top that describes what the code does.  Also add comments, as appropriate, throughout the file.
7.  When you get your code working, publish it to a Word document (after changing "input" functions to "p_input").

Hints/techniques to consider while debugging your script:

• To execute a single cell select "" at the MATLAB menu  at the top of the screen (or type "Ctrl-Enter").
• To execute a single cell and move on to the next cell select "" (or "Ctrl-Shift-Enter").
• To execute the entire script go to "" (or "" if the file is already saved).  Hitting the "F5" key also works.
• Before you can "publish" the file to a Word document, the publishing tool needs to be configured.  From the editor window choose .  Change the file type to "doc" and the directory to a convenient place to store the file (perhaps the desktop, or your "H:" drive) as shown below.  You can also review "publishing" in the last lab.
• If you have to go through the publish process more than once, be sure to close the Word document so MATLAB can overwrite it.
• If you are publishing, you must use the "p_input" function instead of the "input" function.  Note: the "p_input" command only works in Hicks - though I can tell you how to access it from outside of Hicks if you want to do so.

To turn in

(via moodle)

Turn in the Word document as well as the MATLAB script.  Grading is as follows:

• 5 pts for clear and thorough commenting of your code.
• 5 pts for clearly written and concise MATLAB code
• 3 pts for clear and appropriate formatting of the Word document
• 3 pts for a correct result (if the code is clearly thought out and presented, the result should be correct)
• 2 pts for turning in the MATLAB (.m) file
• 2 pts for turning in the Word or pdf (.doc or .pdf) file.