Lecture 3

Chapter 3 - Introduction to MATLAB Programming

Synopsis
In this class, we will discuss the content of Chapter 3: Introduction to MATLAB Programming by developing a MATLAB Program. The topics that will be covered include algorithm design, functions, scripts, input, and output.


Daily Quiz

Quiz 3


Programs, Scripts and Functions

Thus far, we have only interactively worked with MATLAB through the Command Window. This can be a great way to perform quick calculations or experiment with new functions, but the real power of computing is realized when we design programs, scripts and functions to execute larger tasks. Instead of entering expressions one-by-one at the command prompt, we will now enter them in an m-file to create scripts and functions. So what are programs, scripts and functions?

Well, we've seen functions before. Built-in functions such as sin and length were used in previous lectures. They are pieces of code that accept an argument (ex. pi/2) and return a value (ex. 1). When you type sin(pi/2), you are making a function call. Unlike functions, scripts do not take arguments, and they do not necessarily return a value. Scripts are a sequence of MATLAB code that perform some task (ex. formatting a plot or running simulations). A script that makes function calls is said to be a MATLAB program. Let's develop a MATLAB program by creating a script that calls a function.

FitByte

Our goal today is to develop a MATLAB program that converts step counts from a pedometer to miles. This program will incorporate many of the elements discussed in Chapter 3: Introduction to MATLAB Programming. To begin, we need an algorithm for accomplishing our goal. An algorithm is a sequence, or list, of steps needed to solve a given problem.

Algorithm

Typically, we develop our algorithm with a top-down approach. This means that we break apart our problem into smaller and smaller chunks until we have manageable tasks for completion. At the top level, our algorithm is one task.

  1. Convert the step count from a pedometer to miles

Although the goal is clear, we may not be sure how to accomplish this algorithm as written. We can break this step into smaller, more manageable tasks.

  1. Get the number of steps from the user
  2. Convert steps to miles
  3. Return the number of miles to the user

By breaking apart the problem, we can more clearly see what this program involves. We will start by creating a m-file called fitByte.m. This file will contain the code to accomplish each of the steps above.

Step 1: Input

There are two primary ways to get input data--from a file or from the keyboard. In this case, we would like a user to enter the number of steps they have taken that day. The easiest way to get the user to enter a value is to prompt them for input. In this case, we can use MATLAB's input function.

1
2
% Get user input
steps = input('Enter your step count: ');

The text used as the argument of input will show up as a prompt for the user. We have suppressed the output with a semicolon to make the interaction with the user cleaner. In fact, you will find that you want to suppress the output of most lines of code in your scripts and function.

Step 2: Conversion

Getting from steps to miles is not the most difficult conversion to make. Deciding how we would like to implement this job require a bit more thought. We are given a number of steps and need to return the value of miles... sounds like we need a function. Creating functions is a great way to build a set of reusable code. After writing a steps2miles function, we can call it anytime we need in the future. As we said, the function needs to accept the argument of steps and return the value of miles--the form should be steps2miles(steps). Inside the function steps2miles, we can make the conversion by multiplying the average distance per step in inches (29 inches) by the number of steps. Then, we simply convert inches to miles with the factor (1 inch = 1.578e-5 miles).

1
2
3
4
5
% Determine the total number of inches traveled
inches = steps * 29;

% Convert inches to miles
miles = inches * 1.578e-05;

As we mentioned, the above code exists in a separate function, and, therefore, lives in a separate m-file called steps2miles.m. To utilize this function in our program, we must call steps2miles from our fitByte.m file. The syntax for calling steps2miles is similar to calling any other built-in function.

% Convert steps to miles
miles = steps2miles(steps);

Step 3: Output

Just like input, we have two primary methods for formatting output--in a file or on the screen. We would like to instantly tell the user the conversion, so we will choose to print the message to the screen. Ideally, the message would say, "Congrats! You've traveled 4 miles." We could do this by passing this string to the function disp, but this would result in us telling every user that they traveled 4 miles. We need to replace 4 with the value store in the variable miles. To do this, we will use the function fprintf. We replace the number 4 with a place holder (ex. %d) that tells MATLAB how to format the value. Below are the different conversion characters that we can use.

%d  integer
%f  float
%c  character
%s  string

We can add additional parameters to the conversion character to indicate the field width. If we would like an integer to always have a width of 7 characters, we can use the place holder %7d. For us, we would like to have a float with two decimal places.

1
2
% Output number of miles traveled
fprintf('Congrats! You''ve traveled %.2f miles\n', miles);  

There are two tricky bits of code in our fprintf statement. Since strings are enclosed by single quotes, we have to do something special to indicate an apostrophe. When MATLAB interprets two consecutive single quotes inside another set of single quotes, it knows to insert an apostrophe. The other bit of confusing code is the \n, or newline. This sequence of characters indicates that we would like MATLAB to move down to the next line. This ensure that the next command prompt >>, will start on the next line instead of after the word miles.

Putting it Together

By taking a top-down approach, we were able to break apart the problem into smaller, more manageable jobs. We now have two files, fitByte.m (program) and steps2miles.m (function). When running the fitByte.m file, we are prompted for the number of steps.

>> fitByte
Enter your step count: 

If we enter the value 15,000, we are returned the number of miles in a nicely formatted print statement.

Congrats! You've traveled 6.86 miles

We've just written our first MATLAB program!

M-Files

fitByte.m
steps2miles.m


Final Words

As you can see, linking together simple chunks, or modules, of code produces a much more complex program. But we have really only scratched the surface of MATLAB programming. In the coming lectures, we will learn how to link together more scripts and functions that accept multiple arguments and produce visually appealing plots.