Matlab Tutorial 2

This lab builds on the skills you learned in the first Matlab lab last week. In this lab we will learn about loops, conditional statements and loops within loops (a.k.a. nested loops). I wouldn't be suprised if you need to look back to the previous Matlab exercises every now and then to remind yourself how some of the basics work. Let's just jump right in to it...

Loops

In addition to being able to create script m-files in Matlab to run a series of commands, you can also use more advanced programming practices. Loops provide a means for modifying individual values within a vector or matrix quickly and efficiently. Say, for instance that you had a vector x that you wanted to use to create a new vector (xnew) where each value within the xnew vector is equal to the sum of all the values above its location in the x vector. To do this, you could write a simple m-file with a for loop in it, as shown below.

% sum_x.m
% script to create a new vector from an old vector using a for loop

x = linspace(0,80,25); % Create variable x from 0 to 80 with 25 values
xold=0; % Set old x value to zero
for i = 1:length(x) % Loop through the total number of entries in the vector x
xnew(i) = x(i)+xold; % Set current xnew value to ith value in x plus sum of previous x values
xold = xnew(i); % Set xold value to current xnew value
end % End loop

plot(xnew,x); % Plot results
xlabel('xnew'); ylabel('x'); % Label axes
title('for loop results'); % Add title to plot

>> sum_x

As you can see, the for loop in the script above goes through each value in x from the first to the last (length(x)) and adds each value to the previous and stores that value in the vector xnew.

for loops can be used for all sorts of batch computing and can greatly decrease the time you spend calculating values manually.

Conditional Statements

The more advanced programming features in Matlab also include the ability to use conditional statements to perform simple tests on variables. For instance, in the previous section we plotted values of x and xnew as a line, but perhaps we are interested in highlighting values of xnew that are between 400-800 and also greater than 800. You could modify the code above to do just that using if, elseif and else statements.

% sum_x_cond.m
% script to create some new vectors from an old vector using a for loop and conditional statements

x = linspace(0,80,25); % Create variable x from 0 to 80 with 25 values
xold=0; % Set old x value to zero
for i = 1:length(x) % Loop through the total number of entries in the vector x
xnew(i) = x(i)+xold; % Set current xnew value to ith value in x plus sum of previous x values
if xnew(i) < 400 % Do this if xnew is less than 400
xmid(i)=NaN; % Value is not within middle range, set to NaN
xhigh(i)=NaN; % Value is not within high range, set to NaN
elseif xnew(i) <= 800 % Do this if xnew is between 400 and 800
xmid(i)=xnew(i); % Value is within middle range, set to current xnew value
xhigh(i)=NaN; % Value is not within high range, set to NaN
else % Do this if xnew is greater than 800
xmid(i)=NaN; % Value is not within middle range, set to NaN
xhigh(i)=xnew(i); % Value is within high range, set to current xnew value
end % End if/else statement
xold = xnew(i); % Set current xnew value to xold
end % End loop

plot(xnew,x); % Plot results
xlabel('xnew'); ylabel('x'); % Label axes
title('for loop results'); % Add title to plot
hold on; % Keep previous plots up in background of plot window
plot(xmid,x,'g*'); % Plot xmid values as green stars
plot(xhigh,x,'ro'); % Plot xhigh values as red circles

>> sum_x_cond

The condtional statements allow you to sort through the stored values and create subsets of the variables. In this case, if a number is not within a given range, the value at that location is stored as NaN (Not a number). As you'll see, conditional statements are very powerful and useful.

Nested Loops

Nothing more than a loop inside a loop. Let's look at an example.

% nested_loop.m
% script to plot a cosine function with a nested loop

xdata = (0:2*pi/10:2*pi); % Create variable xdata from 0 to 2pi with 11 values (since it divides by 10)
for j = 1:3 % Sets index j to be from 1 to 3 by 1s
for i = 1:11 % Sets index i to be from 1 to 11 by 1s
zdata(i,j) = cos(xdata(i) - 0.5*(j-1)); % Defines zdata, assigns to its ith row and jth column a cosine function value
end % End inner loop
end % End loop


for i = 1:11 % Sets index i 1 to 11 by 1s and separate zdata into 3 diff columns and matrices Z1, Z2, Z3
Z1(i) = zdata(i,1);
Z2(i) = zdata(i,2);
Z3(i) = zdata(i,3);
end % End loop

plot(xdata,Z1,xdata,Z2,xdata,Z3,'LineWidth',2); % Plot results

>> nested_loop

Lab Exercises

The following exercises are designed to continue to help you apply your more advanced Matlab knowledge and hopefully retain some of the commands introduced in the first Matlab lab. For each of the exercises, you'll be asked to submit some code and/or a plot, and some written responses. The exercises are listed below.

Exercise 1 - If you're starting to feel loopy...

Part a:
In this two-part exercise, you need to create a script m-file that uses a for loop to plot the equation of a line (y = m*x + b) divided by the iteration variable i. For part a, your code should
1. Create a vector x that ranges from -10 to 10 by 0.2.
2. Create a vector y that is the equation of a line with slope m=3 and y-intercept b=0.
3. Use a for loop to loop through the stored x-values and create a variable ymod that is the ith y-value divided by the counter variable i.
4. Plot ymod as a function of x with a black line between points and red circles at the points. Include axes labels and a title too.
5. Contain comments on each line of the code explaining what each line does.

Part b:
1. Using conditional statements, do the following:

ymod = y(i)/i for values of y(i) less than 0
ymod = y for values of y(i) greater than or equal to 0 and less than 12
ymod = 12 for all other values of y(i)

2. Plot ymod as a function of x with a black dashed line between points and blue asterisks at the points. Include axes labels and a title again.
3. Again comment each line of your code, to explain what is going on.

For this exercise, please submit a copy of the code for both section a and b, as well as a printout of each plot generated with your code.

Exercise 2 - Nested Loops

In this exercise, create an m-file similar to the cosine function nested loop example above but
1. Increase the size of Z1, Z2, and Z3 from 11 to 21 elements.
2. Put axes labels on the plots.

For this exercise, please submit a copy of the code with comments on every line explaining the code and a printout of the generated plot.

Exercise 3 - Plotting a river terrace profile


(click image to enlarge)

How about we finally do something related to both your new Matlab skills and geomorphology?

In this exercise, you are given
1. A photograph and vertically exaggerated profile of a river terrace.
2. A bare bones code for plotting 2 profile lines to represent elevation and soil thickness.

For this exercise, please edit and augment the code to produce
1. An elevation profile that mimics the given river terrace profile.
2. A schematic (yet realistic) profile for the soil thickness.

Note: This exercise is modified from the original version from Vanderbilt University.

For this exercise, please submit a copy of the code with comments on every line explaining the code, a printout of the generated plot with axes labeled appropriately, and a brief geomorphic justification for your choice of soil thickness changes with elevation (I'd check your textbook, lecture notes, or other sources to back up your story here - with proper references if necessary).