19
 An Introduction to MATLAB Version 1.1 Department of Mathematical Sciences, University of Bath 0 Introduction 0.1 What is MATLAB? MATLAB is a programming language, just like C, Python, and many others. MATLAB also refers to the editor you will be using to write scripts and functions in this language. If you’ve already learnt a programming language, you might find it easy to transition to MATLAB. However, if you have never tried programming before, some of the concepts may seem foreign and a little daunting. The purpose of this guide is to attempt to bridge the gap for those who have no prior knowledge of coding and allow them to take the first steps towards learning a programming language. 0.2 About this guide This guide has been written by student volunteers, and is constantly in the process of being edited and rewritten to improve it and make it more accessible to students. Because of this, there may be some mistakes and room for improvement. If you would like to help with the writing of this guide or offer suggestions and corrections, please email [email protected] .

MATLAB Guide Complete

Embed Size (px)

Citation preview

Page 1: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 1/19

 

An Introduction to MATLAB

Version 1.1

Department of Mathematical Sciences, University of Bath  

0 Introduction 

0.1 What is MATLAB?

MATLAB is a programming language, just like C, Python, and many others. MATLAB also refers to the

editor you will be using to write scripts and functions in this language. If you’ve already learnt a

programming language, you might find it easy to transition to MATLAB. However, if you have never

tried programming before, some of the concepts may seem foreign and a little daunting. The

purpose of this guide is to attempt to bridge the gap for those who have no prior knowledge of

coding and allow them to take the first steps towards learning a programming language.

0.2 About this guide

This guide has been written by student volunteers, and is constantly in the process of being edited

and rewritten to improve it and make it more accessible to students. Because of this, there may be

some mistakes and room for improvement. If you would like to help with the writing of this guide or

offer suggestions and corrections, please email [email protected].

Page 2: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 2/19

1 Getting started with MATLAB

1.1 The Interface 

Once you open MATLAB, you will be presented with an interface like the one below.

①  Command Window: This is the main workspace where you will type your commands. The

prompt symbol (>>) shows that MATLAB is ready for you to type a command.

② Current Folder: Once you start writing and saving functions, you will need to be in the correct

folder in order to use a function. Double-click on a folder to open it. If you are in the correct folder,

the file names will be in black; if you are not in that folder, the file names will appear in grey with a

faded icon beside them.

③ Workspace: Once you begin using variables, MATLAB will show you which variables are stored by

saving their values in this panel. If you want more information about a variable that is stored,

double-click on its name and a new panel will open, showing its details.

④ Command History: This is a list of the previous commands you have entered into the command

window. If you want to use a command again without typing it all out, you can double-click on a

command in this panel to run it.

⑤ Current Location: Here you can check which folder you are currently in.

⑥ Tools: These are your options, which you can explore later.

① 

③ 

④ 

⑤ 

⑥ 

Page 3: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 3/19

1.2 Basic computation in the command window 

Although MATLAB can be used for writing complex functions, it can also act as a simple calculator. In

this section, you can familiarise yourself with the basic command window and its capabilities by

typing simple commands.

Arithmetic 

MATLAB can perform basic operations, just like a calculator. Try typing each of these into the

command window, and hit enter after each calculation:

2+9

13-4

3*4

55/11

MATLAB will return the answer to the calculation, like so:

ans = 11

MATLAB also has ‘built-in’ functions. Try some of these:

exp(4)

log(23)

sqrt(64)

abs(-3)

There are many more built-in MATLAB functions you can use when writing your own functions, but

you will learn these over time.

1.3 Variables

A core concept in programming is the use of variables. A variable is a name (a string of characters,

beginning with a letter) which is assigned a specific value using the = symbol. You can name your

variable whatever you want  –  it won’t affect the way it functions, but it is a good idea to nameimportant variables something that will help you remember what it is later on. Here is an example,

where the variable named “a” is assigned the value “4”: 

a = 4

It’s as simple as that; just type the above code into the command window (it will return a = 4

again because we have not suppressed the output, but we will learn about that later). Now, the

variable “a” has the number “4” associated with it. Any time you write the letter “a” in the command

window, MATLAB will read it as “4” instead. For example, typing sqrt(a)will return ans = 2,

because MATLAB reads the command as sqrt(4).

Page 4: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 4/19

You can change the number assigned to the variable “a” by typing something else. For example, try 

a = 1

Now, MATLAB has forgotten the value “4” and replaced it with “1” instead. You can check this by

looking at the workspace.

MATLAB has a few built-in variables such as pi. Try the command cos(2*pi).

You can assign a variable name to almost anything in MATLAB, even complex functions and

commands, for example

myNum = sin(4*pi/3) + abs(2*a)

Notice that the variable myNum  refers to other variables, pi  and a. If you change a, the current

value of myNum will not change. You will have to re-assign the variable myNum in order to change its

value.

It is important to know that capitalisation of variables matters. mynum  is not  the same as myNum.

Also note that if you make a typo when calling a variable, MATLAB won’t know! It will simply think

you’re trying to access a variable that you have not yet defined, and give an error message.

1.4 Suppressing outputs 

Until now, every time you create a new variable, MATLAB will return the value of the variable in the

command window right after you’ve defined it. This is known as “printing” the output. This doesn’t

do any harm, but it is slightly unnecessary. When you write functions, you won’t want MATLAB to

print hundreds of values every time it assigns a new value to a variable! In order to suppress anoutput, simply type a semicolon at the end of the line. For example, try this:

x = 23;

It still stores the variable, but it doesn’t parrot back its value. Remember your semicolons, and your

command window will be a much more peaceful place, with no unnecessary outputs!

Page 5: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 5/19

2 Matrices

MATLAB, as I’m sure you’ll hear  again, is the “matrix laboratory”, so the majority of techniques

you’ve learnt so far for matrices can also be used in MATLAB.

2.1 Creating a matrix 

To be able to start using those techniques, you need to tell MATLAB exactly what the matrix looks

like. Here’s how to do it.

Suppose you wanted to create the matrix:

   Then you should type the following into the workspace in MATLAB:

   The “A =” is simply assigning the matrix to the variable name “A”, as we learnt earlier.

The “*“ tells MATLAB that what you’re typing is going to be a matrix. If you use a different kind of

bracket, you won’t get a matrix out when you press enter.

The commas separating the numbers tell the computer that the two numbers either side of the

comma are different elements of the matrix. If you omitted the comma between the 4 and the 3,

you’d get an error telling you that you didn’t put the right number of elements in the matrix.

The semi colon after the 2 means that you are starting a new row of the matrix, you should do this

every time you want to start a new row, so if you want n rows in your matrix, you should have n-1

semi colons between the square brackets.

Finally, closing the square bracket means you’ve finished adding all of the elements to your matrix.

Now just press enter to see it displayed on the screen.

2.2 Common errors

1)  Using the wrong type of bracket

2) 

Trying to enter objects other than numbers as elements3)  Unbalanced numbers of elements on different rows

2.3 Operations with matrices

Suppose you have two matrices, A and B, and you want to add them together. Simply type A+B and

press enter, and MATLAB will display their element-wise sum. Note that instead of creating A and B

separately, you could just create them in the same line, using the notation as above. For example if

you wanted to do the sum:

 

Page 6: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 6/19

You could either type

 Or

       

In exactly the same way, you can multiply two matrices together by changing the “” symbol for the

“” symbol. (Since MATLAB knows that the objects are matrices, it will perform matrix multiplication

in this case rather than element-wise multiplication. If you want to perform element-wise

multiplication on matrices, you must use the operation “.”) 

If you want to perform a certain operation to every element of a matrix A, for example add 3 to each

element, just type A+3. Or to multiply every element by 2, type A*2.

To access a certain element of a matrix, all you need to do is type the name of the matrix, and then

in round brackets immediately next to it type the row the element is on, then the column it ’s in. The

two numbers should be separated by a comma.

So if you had the matrix

[ ]

 

The 7 is on the third row, and in the 1st

 column so you would access it by typing B(3,1) 

2.4 More advanced operations

Of course, you probably learnt to do some more difficult techniques with matrices than you’ve just

seen above. Below are instructions for finding the determinant, inverse and transpose of a given

matrix with the help of matlab.

Determinant: To find the determinant of a matrix A, type det(A) 

Inverse: To find the inverse of a given matrix B, type inv(B) 

To transpose a given matrix C, type transpose(C) 

Page 7: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 7/19

3 Functions

3.1 Creating a new function

In principle, functions in MATLAB work just like they do on paper. You enter a number, which gets

subjected to a set list of commands and then you get given a number back. Only in MATLAB, you can

apply functions to objects other than numbers, such as vectors or matrices. Here’s how: 

Go to “Home --> New --> Function”. A new window like this should open. 

The blue “function” simply tells MATLAB that you are writing a function.   Similarly, the blue 'end'

indicates the end of the function.

3.2 Output arguments

The square brackets containing the words “output_args” are very important –  this is the output

variable of your function. You will probably want to delete “output_args” and replace it with another

name - usually we name this variable something like “out” or “answer”. (Later you will learn to have

multiple output arguments, but for now we will just focus on one.) Like any variable, the name of the

output argument doesn’t matter to MATLAB, but you might find easier to use one of the above

names,  just so you’re sure what it is supposed to be doing. When we use this name inside the

function, MATLAB will set (if left-hand side of =) or use (right-hand side) the value of the function.

The name has no meaning outside the function.

3.3 Naming a function

Just like when we use functions normally, and we use names like () ()(), etc. we need to

give each new function a name, so that MATLAB can distinguish between different functions. The

name of the function should replace the “Untitled” on the right hand side of the equals sign.

3.4 Input arguments

The vast majority of functions we see in MATLAB require us to give at least one input argument. An

input argument is the value (or one of the values) we enter into the function, and it gives us an

answer based on the input argument. For example, say we had a function

 ()

. Then the

input argument would be And if we call the function with the value x=5, then we would have () . Sometimes, we are required to use more than one input argument, that is,

Page 8: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 8/19

the end result depends on two different variables. To do this, all we do on the top line is insert two

variables, separated by a comma.

The number one rule with functions is if you tell MATLAB to do something to a variable, you must  

either have already defined it as an input argument, or you have to have defined it in the function

itself, either as a constant, or something that depends on the input argument(s).

3.5 Commenting (Chapman 28,270)

After you’ve been writing functions for a while, at some point, you’ll have to reuse a function you’ve

previously written. When you do, you may find it hard to understand what you initially wrote. This

can all be avoided by explaining what you are doing as you write the function. This is done by typing

% and then typing a brief statement on what a line of text is supposed to accomplish. You can

recognise comments because the font is green, and MATLAB knows to ignore it, so you can type

anything and it won’t  count as part of the code. When you first start programming, you should

comment on anything apart from the blindingly obvious, as it is good practice, but as you becomemore experienced you’ll only need to comment on more complicated parts , because you’ll 

understand the code more.

3.6 Error Checking

It is a fundamental fact of some functions that you can’t just input any old argument and expect to

get a logical answer. For example, try as we might, we can’t come up with a real solution to (), because the function is not defined for that value. In this respect MATLAB is the

same in that some functions just won’t work for some input values. 

It is regarded as good programming practice to account for these undefined areas at the start of

your code, and it is referred to as “error checking”. The best thing we can do is just to stop the code

running as soon as we discover we have a variable that won’t give a sensible answer.

Why should we do this? Well in some cases, a variable won’t just give an answer or return an error,

it will carry on running on and on infinitely, which is obviously a problem. So we can stop the

function from doing this if we discover the problem early enough.

This is where if/else statements (-Chapman 213) come in handy. If we know a function won’t work

for certain values, then we can issue statements before the main part of the function which stop the

function before it can run into trouble. There is an explanation of if/else statements in chapter 4,and a guide for debugging in chapter 6, but here is an example of a function that you can come back

to later once you understand these topics.

3.7 The factorial function (Chapman 328) 

This is a great opportunity for us to consolidate some of the things we’ve seen so far. We’ll do so  by

looking at the factorial function (which you’ll see or will have already seen in JHD’s lectures).

Page 9: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 9/19

Page 10: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 10/19

Note that if we want to print words in MATLAB, we have to put quotation marks around them

The error function (seen above, also see Chapman 286 ) is perhaps the slicker way of dealing with

the problem, as at some point in your MATLAB career, you’re going to have to write what are called

“subfunctions”  (-Chapman 321-323), which are functions which have the sole purpose of assisting

another function. The great thing about the error function is if the error is picked up in the

subfunction, MATLAB still prints the error on the main screen, so you know exactly what has gone

wrong, whereas the “one off” answer, while avoiding an error in one place, might create a much

more confusing error somewhere else. Don’t worry if this sounds confusing, it will make much more

sense once you start using subfunctions regularly.

3.8 Recursion (Chapman 328) 

Perhaps the first time you looked at the last line of the code two pages ago, you were a bit confused.

That’s not a problem, because it used a technique called recursion, which you’ll probably have seen

in some way before, but you might not have realised it.

The last line looks like this:

Now, if someone asked you what 8! was, you probably wouldn’t be able to tell them straight away,

but it wouldn’t  take long to work out. You know that 1!=1 and 2!=2*1! and so on until you get to

8!=8*7!=40320. This is all that the line of code above is doing. MATLAB does n’t know straight away

what Factorial(n) is as a number, but it has an equation for it. In order for MATLAB to solve thatequation it needs to know what Factorial(n-1) is, so it tries to solve the similar expression for

Factorial(n-1), but it runs into the same problem again and again until, finally, it reaches the “base

case”, which is a number for which we have told MATLAB the actual answer. Now, MATLAB is able to

assign a number to Factorial(1), and because it has a number for Factorial(1), it can give one to

Factorial(2), and so on, until it reaches all the way to Factorial(n).

At this point you’re probably thinking how slow and laborious that process seems. If so, you’re right,

it is. For us. But not for MATLAB. In fact to demonstrate how quick MATLAB is, Factorial(100), a

number which in standard form is approximately , can be computed in less than 0.0075

seconds. The point is that recursion is usually a fast and effective way of writing a function. Otherexamples you will see in the course include the Fibonacci numbers, and a method of sorting lists of

numbers called merge sort. Both conform to the same basic idea. The output is simply the function

itself, except the input argument is a smaller number (or list of numbers), and this process continues

until the function hits the base case.

*Note to the reader: Try googling “recursion”. If you understand the joke then you already

understand the topic!]

3.9 Global variables (Chapman 290-291) 

You’ve already seen how to allocate variables, and global variables are merely a way of linking up

variables in several areas. Normally, if you create a function with the variable “x” in it, and also

Page 11: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 11/19

create a variable in the base workspace (on the main page) called “x”, then these two variables are

very much distinct, they are linked in name only. However, if you write in the base workspace

“global x” and the same in your function, then the variable “x” in the function is the variable in the

base workspace. They are identical. You can tell a variable has been globalised because it should be

displayed in a bright blue font.

4 Control Structures

4.1 If-else expressions

Using an if-else expression allows your function to follow different sets of instructions depending on

whether a condition is true or  false. It is best to demonstrate using a simple example, in the context

of a function.

function [ out ] = compare( in )

if in < 3out = ‘Your number is less than three!’; 

elseif in == 3

out = ‘Your number is equal to three!’; 

else

out = ‘Your number is less than three!’; 

end

end

This will create a function with one input, which should be a number. The function will then tell you

whether your number is less than, more than, or equal to 3. This may not seem like a revolutionary

function, but once you understand if/else statements you will be able to use them to create much

more complicated functinos!

Now let’s go through it step by step. The first word that you need to type is if. This lets MATLAB

know that you’re starting to use one of its special in-built control structures. in is just our variable,

and we are comparing it to the number 3. MATLAB will only  continue to the next line if in  is less

than 3; otherwise it will move on to the next statement, the elseif. You can have as many

elseif statements as you want, depending on how many conditions there are, or you can have

none at all! The elseif is very similar to if (it does exactly the same thing), but you can only have

one if, and it must be at the beginning. Once again, MATLAB will compare in to 3, and if they areequal it will continue with the next line (printing “Your number is equal to three!” to the command

window), but otherwise, it will move straight on to the next statement – in this case, else.

Before we talk about else, notice that we used a double equals sign (==). This is different to a

single equals. A single equals is used to assign  a value to something, but a double equals is used

when you’re asking a question: in this case, we are asking “is in equal to 3?” so we use a double

equals. Your if-else structure won’t work if you use = when you should be using ==, so make sure you

learn the difference!

Finally, MATLAB will look at the else condition. You don’t have to have an else condition, but youcan’t have more than one. MATLAB will only go to this line of code if none of the previous conditions

Page 12: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 12/19

have been satisfied, and all  cases that do not satisfy previous if or elseif statements will end up

here. If you want to cover all situations, you probably want an else; if you only want your code to

continue in a few specific situations, you might not want to use one.

End your if-else structure with an end, so MATLAB knows that you’re done. It will automatically

indent your end.

4.2 For and while loops 

For loops and while loops are quite similar to if-else structures, but they are used to cycle through a

number of iterations of a command.

4.2.a For loops

Here is an example of a simple for loop:

for i = 1:10

A(i)=i^2;

end

This simple script will create a row vector named A which contains the squares of the numbers 1 to

10. Let’s look at it step-by-step.

As before, start your structure by typing the for command, which MATLAB will recognise as an in-

built structure. Now, you need to define the number of times you want the loop to be repeated. Theletter i is just a “counter”, a kind of variable. You can name it anything, but letters like i and j are

common. Notice how we refer to this letter throughout the code. Each iteration, the value of the

variable i will change. We have set the values of i to be 1:10; this means that the value will begin at

1, then increase in intervals of 1, until it reaches the final value of 10. The value increases each time

the end statement is reached.

The middle line of code is just what we want to actually do. In this case, the command will assign the

value i2 the i

th element of a row vector.

Finally, remember to place an end command at the end of the loop.

4.2.b While loops 

These are used less often than for loops, but can be useful in certain situations. A while loop is very

similar to a for loop, but will continue the loop as long as a certain situation is true. Consider the

following:

while 1 < 2

A(1)=1

end

Page 13: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 13/19

This is a very bad  while loop; it will never end! The condition, 1<2, is always true, so the loop

continues infinitely, and will probably crash your computer or produce an error in MATLAB. If your

computer appears to be stuck while executing a loop, press ctrl+c to cancel the command and

prevent a crash.

Page 14: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 14/19

Let’s consider a slightly better example: 

i = 1

while i<10

A(i)=i^2

i = i + 1

end

You may notice that this will do exactly the same as our example of a for loop earlier, but it required

a bit more work: first we had to define the starting place of the variable i, then the condition on it

(<10), and then we had to remember to add 1 each iteration (if you forget this, your code will run to

infinity, just like in the bad example).

It may seem like while loops are not nearly as useful as for loops, but there will be some situations

where a for loop won’t work, so keep them in mind.

5 Types of object

In MATLAB there are many types of object. These objects are used to contain different things. Here

are some of them.

Type of object What it contains How to produce one

Double Vector of numbers [1,2]

Struct Contains many fields

which can contain

char/double objects

Struct(‘classes’,‘algebra’,’stats’-,’pupils’,20,200- 

This produces a structure that corresponds the

class ‘algebra’ with 20 pupils

Cell A cell can contain

anything in each

element is not

restricted

‘cat’,*1,3,5+,2-- 

Char Contains a string ‘cat’ 

Page 15: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 15/19

6 Debugging

6.1 MATLAB errors

As you write in MATLAB you will eventually come across error messages that appear when a

function or command tries to compute something outside of the boundaries of what has been

defined. Very often your functions will contain bugs (errors) that may not have been intended but

will show up in the command window as the program runs. MATLAB will often show errors in

programs by underlining the code with red lines (note that these can occasionally appear even

though the program works).

There are four main types of errors: syntax, run-time, logical and typographical. Here are a few

examples:

  Syntax Error: (Parenthesis Error)

These are errors where brackets or certain characters are missing from a statement.

x = (y + 10 ) / 4)

Error: Unbalanced or unexpected parenthesis or bracket.

  Run-Time Error:

These appear when an infinite loop or statement appears that MATLAB cannot compute.

1/0

ans =

Inf

  Logical Error:

These are errors that occur when a program runs but the wrong answer is given.

A = [1,2,3,4,5];

A(1,6) =

Index exceeds matrix dimensions

 

Typographical Errors:

These errors are similar to syntax errors in the sense that they often produce the same message.

A = [1,2,3}

Error: Expression or statement is incorrect or possibly unbalanced.

6.2 Debugging steps

Debugging involves looking for the bugs that cause your program to malfunction and display an error

message. This can involve running the program line-by-line or by pointing out exactly where the

error has occurred.

Page 16: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 16/19

A simple step in debugging is to output each variable after a logical statement by not supressing the

output with semi-colons. Another approach is to use ‘breakpoints’ that make the program stop on

the line of code that has caused the error. This is often very effective as mistakes are most

commonly typographical. To access these tools we use the editor tab when editing a program.

6.3 Presentation of code: indentation/commenting style

When programming, the presentation of code is very important when it comes to assessors or even

yourself re-reading code. Comments made using the % key are important in describing what a piece

of code is trying to do and how it does it. It is very easy to forget what complex code computes after

not looking at it for some time!

Comments:

These should be very concise and straight to the point with no unnecessary points such as:

%The variable L shows length of vector A.

A = [1,2,3];

L = length(A)

L =

3

They should be specific to the commands given and not to clutter up code:

%Loop adds one to the count variable sum each iteration.

sum = 0;

for i = 1:10

sum = sum + 1;

end

Page 17: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 17/19

Indentation:

Code can be quickly neatened up and indented by selecting all code and then pressing ctrl-I. This

lines up all if-end, for-end etc. statements appropriately so that code can run smoothly and looks

neat.

6.4 Timing for efficiency

Efficiency is very important in programming as it determines how expensive an algorithm will be to

use by checking the number of elementary operations (elops) used in a program. These are

operations or logical connectives such as +,-,*,/,<,>,== etc. These will play a big part in the type of

algorithm you should use for a function.

6.5 Error checking in your own functions

In your own algorithms you may want to check for errors yourself in cases where an algorithm will

not run properly. For example when dividing by zero or using non integer values as inputs. One wayto do this is using the error command. This involves typing error(‘string’) with your message

represented by the string of characters inside the brackets. For example:

if y == 0

error(‘Cannot divide by zero’); 

end

Page 18: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 18/19

7 Appendix 

7.1 Crib sheet

Function Description Example

Trig functions cos Give cos radians cos(pi/2)=0sin Give sin radians sin(pi/2)=1

tan Give tan radians tan(pi/4)=1

exp Gives ex e0=1

cosh Gives cosh

Fundamental abs Gives absolute

value

abs(-3)=3

sqrt Gives square root sqrt(49)=7

rem Gives remainder rem(11,2)=1

fix Rounds towards 0 fix(9.9999)=9

floor Rounds down to

nearest integer

floor(4.7)=4

ceil Rounds up to the

nearest integer

ceil(1.1)=2

round Rounds towards the

nearest integer

round(6.7)=7

Vector functions all Gives 1 if all

elements are non-

zero

all([1,2,3,0])=0

any Gives 1 if any

elements are non-

zero

any([1,2,3,0])=1

max Gives max value of

a vector

max([3,7,1,2,4])=7

mean Gives mean value of

a vector

mean([1,2,3,4,5])=3

median Gives median value

of a vector

median([2,3,4,7,8])=4

min Gives min value of a

vector

min([2,3,4,7,8])=2

prod Gives the product of

all the elements

prod([1,2,3,2])=12

std Gives the standarddeviation of a set

std([2,3,4,5])=1.290

sum Gives the sum of

the vector

sum([2,4,6,1])=13

length Gives the length of

the vector

length([2,4,6,3,6,7])=7

size Gives the size of the

vector

size([2,4,3,2],2)=4

det Finds the matrix

determinant

det([2,1;1,2])=3

Functions If if n == 0

error(‘Error’) end

Page 19: MATLAB Guide Complete

8/10/2019 MATLAB Guide Complete

http://slidepdf.com/reader/full/matlab-guide-complete 19/19

  while while t<3

a = a + b;

end

for for i=1:3

A(i)=i^2

end

return Used to break out

of a function or

loop prematurely

return

break Terminates the

execution of a for or

while loop

break

fprintf Formats the output

in specific ways

fprintf(formatstr,arg1,…) 

zeros Create an m*n

matrix of zeroes

zeros(m,n)

isempty Returns TRUE if a

matrix is empty and

FALSE if not

isempty(A)

7.2 Other resources 

  MathWorks tutorials for MATLAB: http://www.mathworks.co.uk/help/matlab/getting-

started-with-matlab.html?s_tid=doc_12b 

  Codecademy tutorials for programming: http://www.codecademy.com/