Introduction To MATLAB Programming

The Basics

In this unit, you will learn how to use the MATLAB® command prompt for performing calculations and creating variables. Exercises include basic operations, and are designed to help you get familiar with the basics of the MATLAB interface. One of MATLAB’s conveniences is its ability to work with lists of numbers. You will have the opportunity to practice constructing and manipulating lists, vectors, and matrices. Since the unit also serves as an introduction to programming, you will receive guidance on defining variables, storing values in variables, and changing the values of variables.

What is Programming?

Every computer is a machine. It does not think. It cannot understand. It does not know what you want it to do.

Everything you want it to do must be told to it, explicitly in its language. In this course we are discussing the MATLAB® syntax.

When you run MATLAB for the first time, you will see a screen that has various parts. The important one for now is the “Command Window.” To close all the others, open the “Desktop” menu and unselect all selected options, except for “Command Window.” You should have now, a single frame, which is white, expect for “>>” and, perhaps a blinking cursor.

Command Prompt and Expressions

At its heart, MATLAB® is a big calculator. To calculate something simply type it in at the “command prompt” and press Enter. Thus, to calculate 1 + 1 we type it in and press Enter. The screen should show:

>> 1+1
ans =

meaning that the answer is 2.

Exercise 1. Run MATLAB, find the command window and the blinking cursor. Find the answer to the following arithmetic problems:

  • 1234+4321=?
  • 104765=?
  • 4733=?
  • 34=? (The operator for “power” is the circumflex ^, usually found by pressing Shift ⇑ 6
  • How far is 192 from its approximation 202220 (Remember that (ab)2=a22ab+b2thus the answer should be ±1)
  • Find an approximation to 1/73
  • Find an approximation to 31 (while you can of course use the fact that x=x0.5, you can also “look for” a dedicated function square root by learning how to use the lookfor command….)
  • If you get 5% interest-rate (yearly) on a loan, compounded monthly, and you start with $1000, how much money will you have after 20 years? (don’t be confused by an answer of the form 2.7e3 which simply means 2.7×103)
  • If two sides of a right triangle have lengths 31 and 45, what is the length of the hypotenuse?

You may have noticed in the exercises that the answer is only given with 5 digits of accuracy (at most). For example, we can ask MATLAB for the value of π and get:

>> pi
ans =

Internally, MATLAB keeps a 16 (more-or-less) digit version of the number it shows us, but to keep things orderly, it only displays the answer rounded to show 5 digits (by default). We can change this by issuing a command:

>> format long
>> pi 
ans =

We can see this, by subtracting part of π from ans, which always holds the full, unrounded answer to the previous, unassigned expression:

>> format short
>> pi 
ans =
>> ans-3.1415
ans =
>> ans - 9.2653e-5
ans =

Exercise 2. Remember the cosine rule? c2=a2+b22abcos(θ). Find the length of the hypotenuse of a triangle with angle 30ο, and sides with lengths 10 and 20. The MATLAB trigono­metric functions (cos, sin, tan) use radians, so you will need to convert using π.

Lists, Vectors, and Matrices

MATLAB® is particularly convenient at calculating with lists of numbers. In fact, it was built for manipulating two-dimensional lists called matrices. An n-by-m matrix has n rows and m columns of numbers, and many MATLAB commands know how to work correctly and efficiently with them.

For example, if we have 10 grocery items whose price we would like to add up, we can write

>> sum(1)
ans =

Here we used a function sum and its argument was a (row) vector we created “manually”. Other vectors have shorthand notation (try them out with various numbers):

  • Many zeros: zeros(n,m) (n and m must be positive integers)
  • Many ones: ones(n,m) (same)
  • An increasing list (step =1): n:m (m must be greater than n)
  • An increasing list with step-size sn:s:m (m might not be the last element of the list)
  • A column vector (manual): [3 ; 2; 6 ; 7] (notice the semicolons)
  • A column of increasing numbers (using transpose) (n:m)'

Exercise 3.

Do the following practice exercises:

  • Try out sequences with step-size 1[4:0.1:5][5:-2:-5].
  • Create a list of the whole numbers between 10 and 20 (inclusive), find their sum.
  • Create the vector of the previous question in decreasing order.
  • Find the sum of the odd numbers between 100 and 200.

Show 1 footnote

  1. 35 3.45 10.55 12.32 1.99 5.43 2.66 3.78 10.21


Often, a result of some calculation is needed for later use, or perhaps a complicated expression can be examined more carefully if done in parts. Both can be done by the use of “variables”. Variables hold whatever result you put in them by the use of the equal sign (=):

  • x=1 creates a variable called “x” and stores the value “1” in it. If one then types “x” in an expression, MATLAB® will use the value stored in “x”, i.e., “1”.
  • Similarly one can define variables to hold anything that MATLAB can calculate.
  • You can easily overwrite a variable with a new assignment: x=2 now the variable x “contains” the value “2”.
  • One can use x as part of an expression: x^2+x-cos(x)
  • Or to create a new variable: y= x^2+7
  • A variable can be a vector (or matrix): A= [1 2 3 4]
  • One can change just a part of AA(3)= 0

In this last example, we are getting ahead of ourselves by referring to an element of a vector. We will touch on that more later.

Note that you can “hide” important MATLAB functions and constants by defining a variable with the same name: pi=3 will give interesting results later (to remove clear pi). This is usually not a good idea, so take care before using a nice name like sumexp, or det, as these are all built-in functions. You can check if a variable is already in use by using the which command:

>> which pi built-in (/Applications/

tells us that pi is a built-in function, while

>> which Pi 'Pi' not found.

tells us that Pi is unused. The difference is in the capitalization. MATLAB-defined functions will always use lower-case names (even if the helpfile will show these as all CAPITAL), which implies that you can always avoid collision by capitalizing the fiirst letter of your variable and functions names.

Homework 1

  1. Let x=1 and y=2Exchange the values of these two variables without specif­ically using ‘1’ or ‘2’ i.e., the exchange should work regardless of the values held by the variables. Hint: You can invent a new variable. Another Hint: Imagine you have misplaced your kids’ breakfast and now Tom’s Cornflakes are in Sally’s bowl and Sally’s CocoPuffs are in Tom’s bowl. You have already poured the milk, how can you fix the problem without throwing away and starting over?
  2. Repeat some of the previous exercises using variables.