Practical 1: Introduction to MATLAB

Site: learnonline
Course: MATLAB
Book: Practical 1: Introduction to MATLAB
Printed by: Guest user
Date: Saturday, 23 November 2024, 3:21 PM

Description

MATLAB Short Course

Practical 1

An Introduction to MATLAB

 

1. MATLABGet a general understanding of the purpose of MATLAB.

2. Understand the MATLAB Workspace

  1. start up MATLAB
  2. type commands in main window
  3. change current directory

3. Use MATLAB as a calculator

  1. perform some arithmetic calculations
  2. understand the importance of operators, and functions
  3. use MATLAB’s help files
  4. use functions like , x sinxcos, \left|x\right| or to solve problems

Working Through This Practical

Go through this practical at your own pace and learn about the MATLAB environment in more detail.

  • The exercises are indented and on separate pages with shaded areas. Do these!
  • Ask your MATLAB eTutor if you have any questions or need advice using the Practical's Forum
  • MATLAB code will always be denoted by the Courier font.
  • An arrow > at the start of the line in an exercise indicates an activity for you to complete.
  • Use the arrows on the top right and bottom right of this display to move between pages, or select a page using the left hand navigation pane.
  • You can also print this resource as a single document (using the print icon in 1.9 or the Admin section in 2.5/2.6).

Please submit your responses to the activities within this practical for formative feedback from your MATLAB eTutor. This word document template can be used to prepare your responses for submission.

Open MATLAB

MATLAB is a powerful mathematical software package used by both engineers and mathematicians in the workplace. The name stands for MATrix LABoratory. Originally designed for manipulating matrices, MATLAB is great for many different mathematical tasks.

Some good reasons for learning MATLAB include:

  • It will allow you to check your assignment/homework calculations
  • You will gain a better insight into mathematical functions through complex graphing that can’t easily be done by hand
  • You can quickly find solutions to problems that take a long time by hand (like finding the determinant of a 5x5 matrix)
  • Later, you will be able to find approximate numerical solutions to problems that can’t be solved by hand (like complicated integrals).

Watch this video on opening MATLAB within the OUA virtual desktop and learn about the MATLAB Desktop Layout.

 

The MATLAB Desktop Layout

layout

The MATLAB layout is divided into 4 windows (white area):

  1. Command Window (centre), where you will type in all commands after the double arrow “>>”
  2. Command History (bottom right), showing a history of commands in the order you typed them.
  3. Workspace (top right), which will show your current variables. We will come back to this when we introduce variables.
  4. Current Folder (left) has a toolbar with your current directory shown. All your work will be saved in this directory.

At the top of the screen in the grey coloured area you will see tabs Home, Plots and Apps. When you start MATLAB it shows all menu items (modes) in Home tab grouped by their function. At the bottom of grey coloured area you will see names of the functional groups for a particular tab.

MATLAB Terminology

At the top of the screen you can see grey coloured area - the MATLAB Toolstrip.

layout

The Toolstrip organizes MATLAB functionality in a series of tabs. Tabs are divided into sections that contain a series of related controls. The controls are buttons, drop-down menus and other user interface elements that you use to do things in MATLAB. For example, the picture above shows the Home tab with sections for operations on Files, Variables, Code and so forth. The File section has controls to do file related operations including creating scripts (New Script), opening files (Open), and comparing two files (Compare). The light blue bar in the upper right corner called the Quick Access Toolbar.

Global Tabs

When you open the MATLAB R2012b for the first time, you will notice three tabs -- the Home tab, the Plots tab, and the Apps tab. These three tabs are always there no matter what you are doing in MATLAB. For that reason, they are called global tabs. The Home tab, shown below, is where you go to do general purpose operations like creating new files, importing data, managing your workspace, and setting your Desktop layout.

GT1

The Plots tab, shown below, is where you go to create MATLAB Plots. The Plots tab displays a gallery of plots available in MATLAB and any toolboxes that were installed. To create a plot from the gallery, you select the variables in the Workspace that you want to plot and then select the type of visualization you want to use for that data. The downward facing arrow on the far right brings down the full extent of the plot gallery with many more choices. The gallery is smart, only showing plots that are appropriate for the data that you've selected.

GT2

The last of the global tabs is the Apps tab, shown below. It is the place you go to run interactive MATLAB applications. The Apps tab presents a gallery of installed applications. The downward facing arrow on the far right brings down the full extent of the applications gallery with many more choices. To start an application you simply click on the correspondent icon.

GT3

Contextual Tabs

As we've seen, global tabs are always present regardless of what you are doing in MATLAB. In addition to global tabs, the Toolstrip also has contexual tabs. Contextual tabs only appear when you're doing certain things in MATLAB. Let's look at the Editor as an example. When you edit a file, three new tabs appear -- the Editor tab, Publish tab, and View tab.

The Editor tab, shown above, contains all the functions you need when you're editing your file. All of those great capabilities of the Editor are there organized in a way to make them easier to find and use. This window opens over the Desktop layout.

Editor Actions

In the upper right corner of the Editor window (and any other window) you will find Actions button. After clicking on it and choosing Dock option the Command window area in the Desktop becomes divided on two parts with the Editor window placed at the top and the Command window at the bottom. If the Editor is docked in the Desktop, those tabs related to the Editor appear next to the global tabs as shown below.

Editor

Publishing is a very useful feature in MATLAB. The Publish tab takes all the formatting controls you need to create beautiful MATLAB documents with publishing and puts them in a single place.

publish ribbon

The View tab is the last of the Editor contextual tabs. It is where you go to control the layout and appearance of files in the Editor. You'll also find contextual tabs in the Variable Editor. These features of MATLAB will be discussed later in our practicals.

Minimizing the Toolstrip

To Minimize the Toolstrip right-click anywhere in the Toolstrip and select "Minimize Toolstrip" or double-click on any of the tabs. To restore the Toolstrip right-click anywhere on the Toolstrip and select "Restore Toolstrip" or double-click on any of the tabs. When the toolstrip is minimized it looks like this:

minimised

Understanding the Desktop layout

> Change your MATLAB Current Folder to a folder on your USB drive. The folder you choose will be where your MATLAB documents are saved.

> To understand better the purpose of the three windows, type in the simple command 3+5 in the Command Window and press enter.
> What happened in the Command, Command History and Workspace Windows?

> To understand better the purpose of the three windows, type in the simple command 3+5 in the Command Window and press enter.

> What happened in the Command, Command History and Workspace Windows?

 

MATLAB as a Calculator

calculatorMATLAB can be used as a powerful calculator. The following exercises demonstrate the order in which MATLAB evaluates expressions.

Calculations in MATLAB

The following commands illustrate the order of priority when evaluating expressions.

Before typing each command into your Command Window, think about what you expect the answer to be. If the output differs from your expected answer, figure out why.

> Type in the following commands, pressing Enter after each one.

5*2+3

3+5*2

> What if instead, we want to add 3 to 5 and then multiply the result by 2? We can use brackets to change the order of evaluation as MATLAB will evaluate the contents of each bracket pair first.

> Type in the following line of code:

(3+5)*2

wink Coding tip: Many students have troubles matching bracket pairs. Experienced MATLAB users reduce these errors by

1. typing both brackets (  ),

2. then using the back arrow key ← to move back and fill in the bracket contents (3+5).

> The following code is not valid. Type it in, press Enter, then read the error message and change the code so that it works (note the vertical line pointing to the first error).

2(3-5)

wink Coding tip: The up-arrow key ↑ on the keyboard will recall a previous line for you to edit.

> Type in the following lines to figure out what the hat ^ key represents.

3^2

3^3

> Figure out the answers you would expect for the following two lines of code and then type them in to verify your answer.

9-3^2

81/3^2

 

 

Self test

Use this self test quiz (also embedded below) to test your understanding so far

 

 

Mathematical symbols in MATLAB

As we have just seen, the simplest mathematical operators are represented by the following symbols.

 

Symbol Operator Order Order of Priority
^ Raise to a power 1 evaluated first
* Multiplication 2 evaluated after any powers
/ Division 2 evaluated after any powers
+ Addition 3 evaluated after any powers, multiplication and division
- Subtraction 3 evaluated after any powers, multiplication and division

Order of Operation

Operation order of Priority

  • The power operator has the highest order of priority.
  • Multiplication and division both have equal 2nd order of priority.
  • Addition and subtraction both have equal 3rd order of priority.

‘Left-to-right’ rule

Expressions are evaluated from left to right: the leftmost operation is performed first and the rightmost operation is performed last. However, note that the operator order of priority supersedes the above left-to-right rule.

Brackets

Round brackets, ( ), can be used to change the order of operations: any expression enclosed in brackets will be calculated first

Exploring the effect of brackets

 

> Type the following arithmetic expressions in the Command Window. Remember to mentally calculate the answers before pressing the Enter key

(8+6)/(10-2^3)

8+6/(10-2^3)

8+6/10-2^3

wink Coding tip: The up-arrow on the keyboard will recall a previous line for you to edit.

Minimising required brackets

 

The following expressions both have a value of 12.

> Type in the equivalent MATLAB expressions to obtain the correct answer using as few pairs of brackets as possible.

 

  1.  \frac{17}{ 2/3 + 3/4 } (needs 1 pair of brackets)
  2. 5+ \frac{9^{ \frac{3}{2} }+1}{2 \left(5-3\right)} (needs 3 or 4 pairs of brackets)

 

Elementary Mathematical Functions

MATLAB has a number of built-in functions, such as square root, sine, cosine, exponential, etc, functions. The following table gives a list of some commonly used functions. Later you will also write your own functions.

round(x) Rounds x to the nearest integer
floor(x) Rounds x down to nearest integer
ceil(x) Rounds x up to nearest integer
rem(y,x) Remainder after dividing y by x (eg remainder of 17/3 is 2)
sign(x) Returns -1 if x; returns 0 if x=0; returns 1 if x>0.
rand or rand(1) Generates a random number between 0 and 1
exp(x) Exponential function e^{x}
log(x) Natural logarithm function, y= \ln x (where e^{y} = x)
sqrt(x) Square root function,  \sqrt{x}
abs(x) Absolute value function, \left|x\right|
sin(x) sine function  \sin x
cos(x) cos function  \cos x
tan(x) tan function  \tan x

Using Mathematical Functions

 

> Let  x = 1.2 . Verify that the following expressions have the values shown, by typing in the correct MATLAB commands.

 

Mathematical expression Answer MATLAB command/Tips
 \frac{1}{ \sqrt{2 \Pi } }e^{- \frac{1}{2}x^{2}} 0.1942 1/sqrt(2*pi)*exp(-0.5*1.2^2)
 \frac{ \sqrt[3]{5+cos4x} }{\left|sin3x\right|} 3.8866 (5+cos(4*1.2))^(1/3)/abs(sin(3*1.2))
 \sin^{2}\left( \pi x\right) 0.3455 Sets of brackets required: 1
 \frac{e^{ \sin x}}{ \sqrt{x^{2}+1} } 1.6259 Sets of brackets required: 3
x \arctan x- \frac{1}{2} \ln \left(1+x^{2}\right) 0.6053 Note: you will need to look up the arctangent function in the MATLAB help files (click on Help at the top menu). Sets of brackets required: 3

Kiwi Change

Watch this video for guidance on how to complete this exercise

You go to the supermarket only to find you left your wallet at home. After hunting on the floor of your rather messy car, you find 95c and decide to buy some kiwi fruit, which are 35c each.

> Use the floor and rem functions to find out the answers to the following questions:

How many kiwi fruit can you buy?

How much change do you have left?

Explain the coding that you used.

 

 

Questions?

You may also wish to discuss these questions within the Practical 1 forum, also embedded below. If you think you know the answer, you are welcome to respond.

 

Submit

Please submit your response to Practical 1 for feedback (also embedded below). Use this word document as a template.