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=?\)
  • \(104-765=?\)
  • \(47*33=?\)
  • \(3^4=?\) (The operator for "power" is the circumflex ^, usually found by pressing Shift ⇑ 6
  • How far is \(19^2\) from its approximation \(20^2-2*20\) (Remember that \((a-b)^2=a^2-2ab+b^2\), thus the answer should be ±1)
  • Find an approximation to 1/73
  • Find an approximation to \(\sqrt{31}\) (while you can of course use the fact that \(\sqrt{x}=x^{0.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\times10^3\))
  • 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 \(\pi\) 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 \(\pi\) 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? \(c^2=a^2+b^2-2a b\, \cos(\theta)\). 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 \(\pi\).

For guided practice and further exploration of how to use the command prompt, watch Video Lecture 2: The Command Prompt.