Using MATLAB as a Calculator


This project is designed to give you a brief introduction to the
MATLAB software which will be used to help carry out your computer
projects during this semester. This software is especially designed
for mathematical, scientific and engineering applications.

Many of you probably have already used a scientific or graphics
calculator like the TI-84. In its simplest application, MATLAB can be
used just like a graphing calculator. In this project we learn how to
turn math into MATLAB.'' That is, we learn how to ask MATLAB math
questions such as
what is 2+2?''

New MATLAB topics

New MATLAB commands

Starting MATLAB

MATLAB is started by double clicking its desktop icon (on a typical
installation of MATLAB on Windows, other installations may vary). It
consists of several panes. Additionally other windows, such as a help
window or plot window, may appear.

The visible panes in the figure are the *Command Window which
appears on the right side of the window. This window contains the
command line where we type commands for MATLAB to interpret. This
will be our main method to interact with MATLAB. Additionally, in the
upper left pane is a Workspace viewer which shows the
variables that are present in the MATLAB session, and in the lower
left pane the Command History window display the commands you
have entered into the command window.

Commands are typed after the prompt: >>. After they
are typed in, the Enter key is hit to send the command to the
MATLAB interpreter. MATLAB either shows the answer or will respond
with an error message indicating why it couldn't do what was
requested.

Multiple commands may be entered on the same line if the commands are
separated by a semicolon ;, or a comma ,. As well, a
semicolon at the end of a command causes its output not to be printed.


We begin our explorations with MATLAB, by learning how to do simple
arithmetic operations:

For instance, adding \( 2+2 \) is done with

>> 2 + 2

ans =

     4

After typing in the command (2 + 2), we typed the
Enter key. MATLAB responded with an answer of 4.

Some other examples are shown below:

symbol example MATLAB response
addition + >> 3+4
subtraction - >> 5 - 9
multiplication * >> 5*9
division / >> 8/9
exponentiation ^ >> 5^3

The only symbol that may need learning is the ^ for powers.

Assignment

When the command 2 + 2 is typed above, MATLAB evaluates it
and responds with an answer of 4. It then forgets about this
calculation because we didn't ask for it to be saved. In order to save
values we can assign the output to a variable. After doing
this, we can refer to the output by the variable name.

In the example below, we assign the value 18 to the variable a,
the value 21 to the variable b, and the value \( 18-21=-3=a-b \) to
the variable c.

command                MATLAB response
>> a = 18                a = 18
>> b = 21                b = 21
>> c = a - b             c = -3
×

Once a value is assigned to a variable, MATLAB remembers it until that variable is reassigned.

Try predicting the responses to the following MATLAB commands
to check your understanding.

                        MATLAB response    
>> a = 3; b = 4;c = 5;  
>> a=b*c               
>> b/a  
>> a=a-18          
>> a^b                

When you make an assignment, the variable name appears in the
Workspace viewer which appears in the upper left pane of the
initial MATLAB window. You can view the contents of the variable by
double clicking it in the workspace viewer. Otherwise, you can enter
just the variable name in the command line and its contents will be displayed.

What is the output of the following commands:

>> a=3; b=4; c=5;
>> a + b/c


Assigning variables can simplify matters when used wisely. For
example, when evaluating

\[ \frac{(2 - 3) - (-3)}{(-1) + 2}. \]

One way is to write out the whole expression at once:

>> ((2-3)-(-3))/((-1)+2)
ans = 2

There are many parentheses that are needed to get this right. This
can make finding errors in our work tough. If we use spaces (which
are ignored) and intermediate names, we can reduce the chance of a
typing error:

>> top = (2-3) - (-3);
>> bottom = (-1) + 2;
>> top/bottom
ans = 2

This technique makes errors much easier to find.

Use assignment to help you compute
\[ 3 - \frac{3^2 - 2 \cdot 3}{2 \cdot 3 - 2}. \]


What is
\[ 5 - 2/6? \]

Is it \( 5 - 1/3 \) or 3 divided by 6? That is, \( 5 - (2/6) \) or \( (5-2)/6 \)?
We should know that the first is true because division happens before
subtraction. What makes knowing this necessary is because there are
two operations above, subtraction and division, and the answer will
depend on which is done first. The order of operations act like a
traffic cop directing the flow of what happens when. MATLAB uses a
fairly standard order of priority (precedence) for operations:
addition and subtraction have the same priority, which is below
multiplication and division. Powers have the highest priority. So
typing the command

>> 5 - 2/6

returns an answer of 4.6667 or \( 5 - 1/3 \), as division is done before
the subtraction.

In the following exercise you will review the basic order of operations.

Multiplication/Division vs. Addition/Subtraction

“One of these things is not like the others.”

Which of these MATLAB commands is not like the other two? To help you
out, try doing this with some values for \( a \), \( b \) and \( c \) like

>> a= 3; b=13; c= 23;





Which operations have higher precedence?


Multiplication/Division vs. Exponentiation

Repeat the same exercise with the following expressions.






Operations with the same precedence

How does MATLAB interpret the following commands?

>> 3 - 3 - 3
>> 6 / 3 / 2
>> 2 ^ 3 ^ 2

There is an ambiguity as the answers are different if the left most
operation is done first compared to if the right most one is.

×

Note

doing right to left is \( 3 - (3 - 3) \) or \( 6/(3/2) \) or \( 2^{(3^2)} \)

For the following questions do the problem without parentheses and
then again with parentheses doing it from right to left. Answer is
they are the same.

\( 3 - 3 -3 \)


\( 6/3/2 \)


\( 2^3^2 \)


Investigate the expressions below to see the order in which the
operations are performed by MATLAB. (For example, does \( 5-3-2 = (5-3)-2 \) or \( 5 - (3-2) \)?)

>> 5 - 7 - 8                     
>> c - a + b - c
>> 5 / 7 / 8
>> 5 / 7 * 8 * 9

What rule(s) does MATLAB use when evaluating expressions with
two or more operations of the same priority?


Practice what you have just reviewed to evaluate the following. Let

>> a=4;b=5;c=8;

\[ \frac{a^b - c/b}{c - a} \]

\[ \frac{a^{(c - b)}}{c - b} \]

\[ \frac{a^{3/2}}{b} \]

\[ \frac {a - b(c-a)}{c-a} \]

×

Note

A full explanation of priority rules is attached to this project in the Reference Section. You may want to review this to check your answers.

Reusing previous commands

You can save some typing if you learn how to reuse and edit your
previously entered commands. The Command History window shows
the commands you've typed during a MATLAB session. Double clicking on
a command will paste it into the command window. The command history
may also be accessed inside the command line by using either the up or
down arrow to scroll through your previous commands.

Once a command is at the >> prompt, you may make changes to
it. Use the left or right arrows to move around, or the mouse. Then
you may insert text or delete existing text.

Finally, you may type Enter to execute the new command. You
do not need to have the cursor at the end of the line to do this.


MATLAB allows much more than just the basic arithmetic operations.
Extra functionality is provided by functions, such as sin,
cos, or sqrt. A function is referred to by its name
and used by calling the function with its
argument(s) enclosed in matching parentheses. A list of basic
functions and their MATLAB equivalents is attached to the end of the
project in the Reference Section.

For instance, the value of \( \sqrt{15} \) is given by

>> sqrt(15)                     #  ans = 3.8730

(The text after and including the number sign symbol is a comment and
will be ignored if typed in.)

Just typing the function name, without the parentheses, will show its
definition.

Here are a few more examples of function evaluations. Note that to
get \( \pi = 3.1415 \dots \), you type pi; to get the number \( e = e^1 = 2.7182 \dots \), you type exp(1).

When trying these examples, if you get an error message, check that
you have spelled the function name correctly. For example, if you
type sqt(3) (you misspelled sqrt), MATLAB responds with
the error message

      ??? Undefined function or variable sqt.

Try evaluating the following using MATLAB:

                           MATLAB response
>> sqrt(216)               14.6969           
>> pi                      pi = 3.1416... is built-in
>> exp(1)                  ans = 2.7183   e is not built-in
>> sin(pi/4)               ans = 0.70711  
>> x = pi/3                x = 1.0472    assigns x
>> tan(x)                  ans = 1.7321, as x = pi/3 by above
>> sin(x)^2 + cos(x)^2     ans = 1, again, as x = pi/3

Note: you will get better precision if you do not round off intermediate
computations. Try typing the following to see an example:

>> pi/4                         
>> sin(0.785)                   
>> sin(pi/4)
>> sqrt(2)/2
×

Note

When trigonometric functions are evaluated in MATLAB, arguments must be specified in radian measure—not in degrees. Recall, to convert from degrees to radian you muliply by \( \pi/180 \).

Use MATLAB to evaluate the following expressions.

Calculate the sine of 40 degrees using MATLAB. MATLAB uses radians
for all angle measurements. You will need to convert degrees to
radians first.

Evaluate \( \sin^2 65^\circ \)

Evaluate \( e^{(10 - 8.5)/3} \)

Evaluate \( \arcsin(\sin(3\pi/4)) \)



We will often want to apply a function to many different values of
\( x \). We'd like to do this in the most convenient manner. For example,
to compute the function \( f(x) = x^2 \cos^3(x) \) for \( x=\pi/3,\pi/4 \) and
\( \pi/6 \) we can save some work by assigning a value to \( x \) and then
computing:

>> x=pi/3; x^2 * cos(x)^3
>> x=pi/4; x^2 * cos(x)^3
>> x=pi/6; x^2 * cos(x)^3

This allows us to make a single change to \( x \) per line, instead of
changing it in both places.

Although the above technique is useful, there are better ways to do
this task, as the MATLAB language is written to naturally apply the
same function to many different values at once. In order to do so we
need to learn two things:

Defining vectors

We use the term vector to describe a MATLAB variable that contains
lots of numbers at once. Vectors are made in MATLAB using the square
brackets []. (MATLAB refers to vectors as arrays, a more
general concept.)

The simplest way to make a vector is to just type in the numbers you
want inside of matching []:

×

warning

Dont type the part with the % symbol. This is a comment to you.
>> x = [1,1,2,3,5,8,13,21]      % start of Fibonacci sequence
>> x = [1 1 2 3 5 8 13 21]      % commas are optional
>> somePrimes = [2,3,5,7,11,13,17,19,23]
×

Note

The name we give to a vector allows us to refer to the entire collection of numbers later on without needing to type them in again

Which of the following does not store the values 1,2,3 into a vector named x?


Vector arithmetic

Vectors are used by us, as they allow us to do the same operation for
many different values at once. This is similar to what happens when
you use the list mode of your TI calculator. Unfortunately, vectors
have a slightly different algebra than numbers (scalars) and learning
this is an important first step in working with MATLAB to do calculus
problems. Here we see that the usual operators may not work as
expected.

Store the number \( 1,2,3 \) in a vector named x. Answer the following for this vector.

What is x+x?


What is the output of x * x?


We will see more in the next project.

Arithmetic sequences

Many of the vectors of numbers we will deal with will arithmetic sequences:

\[ a, a+h, a+ 2h, a+3h, \dots, a+kh = b, \quad\quad h > 0. \]

We can think of an arithmetic sequence in two ways:

There are two different ways in MATLAB to generate such sequences,
depending on how you think of the values in the sequence.

numbers separated by a step size \( h \)

To generate a sequence of numbers separated by 1 is done using the
: symbol, as in a:b:

>> 1:5                          % 1 2 3 4 5
>> -1:5                         % -1 0 1 2 3 4 5
>> -(1:5)                       % -1 -2 -3 -4 -5 

The last example showing that the minus sign here means multiply each
entry by \( -1 \).

If we want a step size of \( h \) we use this syntax: a:h:b. For
instance:

>> evens = 0:2:10               % even numbers 0,2,4 ... 10
>> evens = 0:2:9                % even numbers 0,2,4 ... 8. Stops at 8
>> skip15 = 0:15:60             % 0,15,30,45,60 -- class is almost done
>> skip15 = 15*(0:4)            % same thing!
>> skipafew = 3:98              % 1 2 skipafew 99 100

Which of these produces the odd numbers between 1 and 99: 1, 3, 5, …, 99


Which of these produces the numbers 10, 20, 30, …, 120


Which of these does not give the numbers 1,2,3,4,5


A fixed number of numbers

When plotting functions we will desire a lot (say 100 or a 1000) of
evenly-spaced numbers between two points. Rather than figure out the
step size between the points it is more convenient to specify how many
*lin*early *space*d points we want. This is done with the linspace
function. Using it as linspace(a,b) will produce 100 numbers between
a and b. You can override the default of 100 using a third
argument:

>> linspace(0,5,6)              % ans = [0 1 2 3 4 5] (6 numbers)
>> linspace(0,pi,3)             % ans = [0, pi/2, pi] (3 numbers)

What linspace command produces this output:

    1.000 1.500 2.000 2.500 3.000 3.500 4.000


What is the last value output by the command

>> linspace(0,pi)

Arithmetic operations with vectors

In MATLAB the basic object is a matrix (a rectangular collection of
numbers). As such, the default definitions for +, -, *, /, and
{} are the matrix definitions. What we will want is a
little different. This means we will need to be careful when we
multiply, divide or take powers of vectors.

This will be discussed more in the next project. For this project, we
focus on arithmetic operations which work as we would like: addition
of vectors of the same size, and multiplication of a vector times a
number (a scalar).

For example

>> x = 1:5                      % the numbers 1 2 3 4 5
>> x + x                        % the numbers 2 4 6 8 10
>> 3*x                          % the numbers 3 6 9 12 15
>> 3*(x - 3)                    % subtract 3 then multiply:
                                %    -6 -3 0 3 6

This allows us to do simple transformations, such as the conversion
from Celsius to Fahrenheit, or back, given by these formulas:

\[ F = 9/5 C + 32 \quad\text{ or }\quad C = 5/9(F - 32) \]

This is the basis of the last exercise.

Find room temperature in Celsius (F = \( 68^\circ \))

Find the average body temperature in Celsius (F = \( 98.6^\circ \))

Let \( X \) be a vector of Fahrenheit values between -100 and 100 in step
size of 20, and \( Y \) be the corresponding Celsius values. Which MATLAB
commands give this?


If two vectors are the same length, a table can be made from them that
allows you to compare their entries. The syntax is either
[X;Y] or [X;Y]'. Look carefully at the table of \( X \)
and \( Y \) values. At what temperature is the Celsius and Fahrenheit
measurement the same?


Order of Operations

MATLAB uses the following symbols for arithmetic operations:

Operation Symbol Precedence Comment
Exponentiation ^ 3 Highest precedence
Multiplication * 2
Division / 2
Addition + 1
Subtraction - 1 Lowest precedence

If an arithmetic expression contains nested parentheses, then the
expressions contained within the innermost parentheses are evaluated
first. In the absence of parentheses, the precedence rules
decide the order of evaluation. The following rules apply:

  1. All operations with a higher precedence are carried out before
    those of lower precedences. Thus exponentiation is carried out
    first, then comes multiplication and division, and finally, addition
    and subtraction.

  2. If two operations have the same precedence then the operation on
    the left is carried out first. This is called the left-to-right scan
    rule.

  3. When necessary, the user must provide the parentheses to achieve
    the desired order of operations.

Basic Functions

MATLAB notation Mathematical notation Meaning of the operation
sqrt(x) \( \sqrt x \) square root
abs(x) \( |x| \) absolute value
sign(x) sign of \( x \) (\( +1 \), \( -1 \), or \( 0 \))
exp(x) \( e^x \) exponential function
log(x) \( \ln x \) natural logarithm
log10(x) \( \log_{10}x \) logarithm base 10
sin(x) \( \sin x \) sine
cos(x) \( \cos x \) cosine
tan(x) \( \tan x \) tangent
asin(x) \( \sin^{-1} x \) inverse sine
acos(x) \( \cos^{-1} x \) inverse cosine
atan(x) \( \tan^{-1} x \) inverse tangent
×

Note

MATLAB may give unexpected results when working with negative numbers, since its default is to assume inputs and outputs are complex numbers. Try evaluating sqrt(-4), (-8)^(1/3), and log(-5), to see what happens. (in MATLABt \( i \) represents \( \sqrt{-1} \).)