Mat Lab Basics

6
MATLAB Basics L M Kalnins, February 2010 Navigation and Tools MATLAB includes a variety of different windows for displaying different types of information and performing specific tasks. Each window can generally be opened/closed, docked in the main window or popped out, and repositioned/resized depending on current needs/preferences. The Window menu helps you navigate between the currently open windows, while the Desktop menu lets you open new windows (which can also be done from the command window). Command Window The window where you type commands and non-graphic output is displayed. A‘>>’ prompt shows you the system is ready for input. The lower left hand corner of the main window also displays ‘Ready’ or ‘Busy’ when the system is waiting or calculating. Previous commands can be accessed using the up arrow to save typing and reduce errors. Typing a few characters restricts this function to commands beginning with those characters. Command History Records commands given that session and recent sessions. Can be used for reference or to copy and paste commands. Workspace Shows the all the variables that you have currently defined and some basic information about each one, including its dimensions, minimum, and maximum values. The icons at the top of the window allow you to perform various basic tasks on variables, creating, saving, deleting, plotting, etc. Double-clicking on a variable opens it in the Variable or Array Editor. All the variables that you’ve defined can be saved from one session to another using File>Save Workspace As (Ctrl-S). The extension for a workspace file is .mat. Current Directory The directory (folder) that MATLAB is currently working in. This is where anything you save will go by default, and it will also influence what files MATLAB can see. You won’t be able to run a script that you saved that you saved in a different directory (unless you give the full directory path), but you can run one that’s in a sub-directory. The Current Directory bar at the top centre of the main window lets you change directory in the usual fashion — you can also use the UNIX commands cd and pwd to navigate through directories. The Current Directory window shows a list of all the files in the current directory. Editor The window where you edit m-files — the files that hold scripts and functions that you’ve defined or are editing — and includes most standard word-processing options and keyboard shortcuts. It can be opened by typing edit in the Command Window. Typing edit myfile will open myfile.m for editing. Multiple files are generally opened as tabs in the same editor window, but they can also be tiled for side by side comparison. Orange warnings and red errors appear as underlining and as bars in the margin. Hovering over them provides more information; clicking on the bar takes you to the relevant bit of text. Also remember that MATLAB runs the last saved version of a file, so you have to save before any changes take effect. Variable Editor or Array Editor Opens variables in an Excel-like format, and is useful for check- ing what data is in which column/row, checking that value is where you meant it to be, etc. Data can also be edited or created in this window. Double-clicking on a variable in the Workspace will open it for editing. Multiple variables are usually opened as tabs, but can also be tiled for 1

Transcript of Mat Lab Basics

Page 1: Mat Lab Basics

MATLAB Basics L M Kalnins, February 2010

Navigation and Tools

MATLAB includes a variety of different windows for displaying different types of information andperforming specific tasks. Each window can generally be opened/closed, docked in the main windowor popped out, and repositioned/resized depending on current needs/preferences. The Window menuhelps you navigate between the currently open windows, while the Desktop menu lets you open newwindows (which can also be done from the command window).

Command Window The window where you type commands and non-graphic output is displayed.A ‘>>’ prompt shows you the system is ready for input. The lower left hand corner of the mainwindow also displays ‘Ready’ or ‘Busy’ when the system is waiting or calculating. Previouscommands can be accessed using the up arrow to save typing and reduce errors. Typing a fewcharacters restricts this function to commands beginning with those characters.

Command History Records commands given that session and recent sessions. Can be used forreference or to copy and paste commands.

Workspace Shows the all the variables that you have currently defined and some basic informationabout each one, including its dimensions, minimum, and maximum values. The icons at the topof the window allow you to perform various basic tasks on variables, creating, saving, deleting,plotting, etc. Double-clicking on a variable opens it in the Variable or Array Editor. Allthe variables that you’ve defined can be saved from one session to another using File>SaveWorkspace As (Ctrl-S). The extension for a workspace file is .mat.

Current Directory The directory (folder) that MATLAB is currently working in. This is whereanything you save will go by default, and it will also influence what files MATLAB can see.You won’t be able to run a script that you saved that you saved in a different directory (unlessyou give the full directory path), but you can run one that’s in a sub-directory. The CurrentDirectory bar at the top centre of the main window lets you change directory in the usualfashion — you can also use the UNIX commands cd and pwd to navigate through directories.The Current Directory window shows a list of all the files in the current directory.

Editor The window where you edit m-files — the files that hold scripts and functions that you’vedefined or are editing — and includes most standard word-processing options and keyboardshortcuts. It can be opened by typing edit in the Command Window. Typing edit myfile willopen myfile.m for editing. Multiple files are generally opened as tabs in the same editor window,but they can also be tiled for side by side comparison. Orange warnings and red errors appear asunderlining and as bars in the margin. Hovering over them provides more information; clickingon the bar takes you to the relevant bit of text. Also remember that MATLAB runs the lastsaved version of a file, so you have to save before any changes take effect.

Variable Editor or Array Editor Opens variables in an Excel-like format, and is useful for check-ing what data is in which column/row, checking that value is where you meant it to be, etc. Datacan also be edited or created in this window. Double-clicking on a variable in the Workspacewill open it for editing. Multiple variables are usually opened as tabs, but can also be tiled for

1

Page 2: Mat Lab Basics

side by side comparison.

Figure Editor MATLAB opens figures in separate windows, which includes the ability to fine-tunethe appearance of the plot, zoom, etc. You can also use the Data Cursor to extract values andsave them to the Workspace. See the Help documentation for further detail. The figures canalso be saved in a wide variety of formats — it’s usually a good idea to save them as an m-file(File>Generate M-file) if there’s any chance at all you might want to modify the figure laterand you haven’t already saved the generating code in a m-file.

MATLAB Help MATLAB’s help documentation is very good, and can tell you pretty much any-thing you need to know. Help>Product Help opens the Help Window, which works largelylike a web browser, including forward and back buttons. Use the Contents tab for help orientedaround a broad topic (most of what you need will be under the MATLAB heading, and thenprobably Getting Starting or Graphics) — Search or Index for more specific queries (e.g. inter-polating values, polynomial fit, etc.). The ‘see also’ at the end of each file is very useful if youhaven’t found quite the right thing. It can also suggest better ways of doing things. Typing helpcommandname in the Command Window will also bring up the help file for that command.

Basic Commands and Formatting

pi, i, 2e6, Inf 3.14159...,√−1, 2× 106, Infinity

+, -, *, / (not \) matrix addition, subtraction, multiplication, and division+, -, .*, ./ (not .\) element-by-element addition, subtraction, multiplication, and divisionxˆn xn

( ) Used to clarify expressions and specify order of operations when nec-essary and to specify elements of an array. MATLAB knows the usualrules for precedence and order of mathematical operations.

[ ] Used to create arrays. Not used to clarify expressions or for order ofoperations.

exp(x), log(x),sqrt(x), abs(x),sin(x)

ex, natural log of x (base 10 log is log10(x)),√

x, |x|, sine of x (in radi-ans). Use the Help window to find virtually any mathematical functionyou can think of.

variable = commands Assign a value or array to a variable name.ans The default variable MATLAB assigns output to if you don’t specify a

variable.command; Adding a ‘;’ to the end of a command prevents the output from being

printed onscreen, especially useful for long arrays or repetitive calcula-tions.

function(arg1, ‘strarg’) Enclose function arguments with ‘()’ and separate with commas. Argu-ments that are strings of characters, rather than variables or numbers,are enclosed with ‘’.

2

Page 3: Mat Lab Basics

[2 3 4; 5 6 7] Enter matrices with ‘[]’ brackets; separate elements of a row by spacesor commas, and start a new row with a ‘;’.

myarray(i,j) Specifies the element in the ith row and the j th column of myarray.Calling an element that doesn’t exist generates an error, but assigninga value to an element that doesn’t exist simply enlarges the array. Thisis a double-edged sword.

min:inc:max Generates a vector going from min to max in increments of inc. If youdon’t give inc, MATLAB assumes an increment of 1.

myarray(i:j,k) Refers to the elements in the ith to j th rows and kth column of myarray.A ‘:’ alone specifies all the rows (or columns) of an array, ‘end’ specifiesthe last row or column.

myarray(:,2) = [ ] Deletes the 2nd column of myarray. Deleting a single element producesan error, since the result isn’t a matrix. Using only a single index, how-ever, deletes the given element(s) and converts the remaining elementsinto a row vector.

p = polyfit(x,y,n) Finds the coefficients p of the polynomial of degree n that best fits datax, y in a least squares sense. The coefficients are given from the highestorder term to the lowest.

polyval(p,x) Returns the value of the polynomial with coefficients p evaluated at x.

Graphics Commands

Most graphics editing can also be done using the Graphics Editor in each figure window, but forcommands you will be running repeated, inclusion in scripts, etc., it is easier to specify them in thecommands. The basics are pretty self-explanatory, but most of the commands have further optionsyou can find in the Help documentation.

plot(x1, y1, x2, y2) Plots x1 versus y1 and x2 versus y2 on a single figurearea(x,y) Plots x versus y, but fills in the area under the curve. Useful if

your figure is trying to be a cross section.hold on/hold off ‘Holds’ the current figure so that subsequent graphing com-

mands are added to it, rather than creating a new figure. Usefulwhen you want to customise each line on a plot.

. . . Lets you continue a command on the next line.xlabel(‘label (units)’) Labels the x axis. Don’t forget the ‘’ around the label.ylabel(‘label (units)’) Labels the x axis. Don’t forget the ‘’ around the label.title(‘Plot Title’) Titles the plot. Don’t forget the ‘’ around the title.axis([xmin xmax ymin max]) Adjusts the axes after plotting.

3

Page 4: Mat Lab Basics

You can customise the plots almost anyway you like, but the most basic options go in a single para-mater, ‘Linespec’, added as an additional argument to plot. It specifies:

Line Type Basic choices, such as ‘-’ for solid, ‘- -’ for dashed, ‘:’ for dotted, etc.

Marker Type Most basic shapes, such as ‘s’ for square, ‘o’ for circle, etc.

Colour A limited number that can be specified with single letters, such as ‘r’ for red, ‘c’ for cyan,etc.

Thus plot(x,y,‘- -sc’) gives a red dashed line with red squares and plot(x,y,‘oc’) gives cyan circles withno line.

There are also more advanced options which let you specify a wider range of colours, control the colourof line and and marker separately, change the thickness of the line and size of the marker, etc. Theseusually show up as a pair of arguments to plot, ‘ParameterName’, ‘ParameterValue’. For example,plot(x, y, ‘- -s’, ‘MarkerFaceColor’,‘g’) turns the markers (squares, in this case), solid green. For awider range of colours, you have to use RGB triplets (in the range 0–1, so if you’re used to giving themout of 255, write them as fractions [55/255 100/255 190/255], etc. RGB triplets (red-green-blue) area common way of specifying colours in computing, and there are charts of colours and their tripletsavailable online (e.g. Wikipedia Web Colours article).

Conditional Statements and Loops

If you’ve done a bit of programming, these will be familiar to you, and it’s only MATLAB’s particularsyntax that you need to learn. If you haven’t done programming before, these are statements thatenable you to write code that will be executed only under certain conditions, e.g. if x < 10 or codethat will execute repeatedly, e.g. while 0 < x < 10.

Logical Expressions

These combine statements which evaluate to either true or false (x <= 10, y == 6, etc.) with thelogical operators & (logical AND), | (logical OR), and ∼ (logical NOT). Note that when testing forequality, you must use ==. A single = assigns the value of the right hand side to the left hand side.If you are used to other programming languages, && and || also work (and short-circuit, which thesingle forms do not).

Sample expressions:x < 10 & y == 4 x is less than 10 and y equals 4x + y >= 100 | x + y < 50 ∼ x == y x + y is greater than or equal to 100 or less than 50 and x

does not equal y

4

Page 5: Mat Lab Basics

Conditional Statements

The basic conditional statement is:

if (logical expression)(code to evaluate if ex-pression is true)

end

e.g. if x < 10b = 2x

end

which says If x is less than 10, setb equal to 2x. If x isgreater than or equal to10, b won’t be assigned anyvalue (or will retain thevalue it had before the ifstatement started.

To evaluate different code for each of several possible alternatives, we have:

if (logical expression)(code to evaluate if expres-sion is true)

elsif (2nd logical expression)(code to evaluate if 2nd ex-pression is true)

...else

(code to evaluate if no expres-sion is true)

end

Here, if the first expression is true, the first batch ofcode is evaluated, and the programme leaves the ifblock of code. If the first expression is false, it triesthe second expression, and so on. Only one batch ofcode is ever evaluated. You can have as many elsifstatements as you need, and you do not have to havean else statement if no code is to be evaluated whenall expressions are false.

These statements can also be nested - you can put another if statement in the code to be evaluated ifa given expression is true, i.e.

if x < 10if y < 10

b = x ∗ yelse

b = x + yelse

b = xend

Note that this is not a particularly sensible set of statements...

If you have different code to be evaluated when an expression is equal to certain values, i.e. you arecontinually testing if x == number, there is a very similar structure called switch that you can (andprobably should) use instead.

Loops

Loops are for when you want to execute a statement a set number of times or for as long as someexpression is true. The for statement is used to evaluate code a set number of times, for example as

5

Page 6: Mat Lab Basics

x goes from 1 to 20:

for (range of values)(code to evaluate foreach value)

end

e.g. b = 0for x = 1 : 20

b = b + x2

end

which Finds the sum of thesquare from 1 to 20. Theb = 0 ensures that any pre-vious value of b doesn’t af-fect the result.

The while statement evaluates a block of code for as long as a given logical expression is true:

while (logical expression)(code to evaluate whileexpression is true)

end

e.g. x = 1while x < 2000

x = 2xend

which Prints the powers of 2 thatare less than 2000. Thex = 1 starts the process offcorrectly.

It is important to make sure that loops will eventually exit. This is particularly important with whileloops. If, for example, you forget to write the statement that changes the value of x you will be testingthe same condition ad infinitem (e.g. 1 < 10, which is always and forever true), and the loop becomesan infinite loop. If your code mysteriously seems to run forever and ever, check for infinite loops.

6