This document provides an overview of the various windows and tools available in MATLAB for displaying information, writing and editing code, and creating figures and plots. It describes the command window, workspace, current directory window, editor, variable editor, figure editor, and help documentation. It also provides examples of basic MATLAB commands and formatting for arithmetic operations, matrices, arrays, polynomials, and creating plots and customizing figures.
This document provides an overview of the various windows and tools available in MATLAB for displaying information, writing and editing code, and creating figures and plots. It describes the command window, workspace, current directory window, editor, variable editor, figure editor, and help documentation. It also provides examples of basic MATLAB commands and formatting for arithmetic operations, matrices, arrays, polynomials, and creating plots and customizing figures.
MATLAB includes a variety of dierent windows for displaying dierent types of information and performing specic 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 dened 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 youve dened can be saved from one session to another using File>Save Workspace As (Ctrl-S). The extension for a workspace le 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 inuence what les MATLAB can see. You wont be able to run a script that you saved that you saved in a dierent directory (unless you give the full directory path), but you can run one thats 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 les in the current directory. Editor The window where you edit m-les the les that hold scripts and functions that youve dened 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 myle will open myle.m for editing. Multiple les 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 le, so you have to save before any changes take eect. 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 side by side comparison. Figure Editor MATLAB opens gures in separate windows, which includes the ability to ne-tune the appearance of the plot, zoom, etc. You can also use the Data Cursor to extract values and save them to the Workspace. See the Help documentation for further detail. The gures can also be saved in a wide variety of formats its usually a good idea to save them as an m-le (File>Generate M-le) if theres any chance at all you might want to modify the gure later and you havent already saved the generating code in a m-le. MATLAB Help MATLABs 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 largely like a web browser, including forward and back buttons. Use the Contents tab for help oriented around a broad topic (most of what you need will be under the MATLAB heading, and then probably Getting Starting or Graphics) Search or Index for more specic queries (e.g. inter- polating values, polynomial t, etc.). The see also at the end of each le is very useful if you havent found quite the right thing. It can also suggest better ways of doing things. Typing help commandname in the Command Window will also bring up the help le for that command. Basic Commands and Formatting pi, i, 2e6, Inf 3.14159...,
1, 2 10 6 , Innity +, -, *, / (not \) matrix addition, subtraction, multiplication, and division +, -, .*, ./ (not .\) element-by-element addition, subtraction, multiplication, and division xn x n ( ) Used to clarify expressions and specify order of operations when nec- essary and to specify elements of an array. MATLAB knows the usual rules for precedence and order of mathematical operations. [ ] Used to create arrays. Not used to clarify expressions or for order of operations. exp(x), log(x), sqrt(x), abs(x), sin(x) e x , natural log of x (base 10 log is log10(x)),
x, |x|, sine of x (in radi-
ans). Use the Help window to nd virtually any mathematical function you can think of. variable = commands Assign a value or array to a variable name. ans The default variable MATLAB assigns output to if you dont 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 [2 3 4; 5 6 7] Enter matrices with [] brackets; separate elements of a row by spaces or commas, and start a new row with a ;. myarray(i,j) Species the element in the i th row and the j th column of myarray. Calling an element that doesnt exist generates an error, but assigning a value to an element that doesnt exist simply enlarges the array. This is a double-edged sword. min:inc:max Generates a vector going from min to max in increments of inc. If you dont give inc, MATLAB assumes an increment of 1. myarray(i:j,k) Refers to the elements in the i th to j th rows and kth column of myarray. A : alone species all the rows (or columns) of an array, end species the last row or column. myarray(:,2) = [ ] Deletes the 2nd column of myarray. Deleting a single element produces an error, since the result isnt a matrix. Using only a single index, how- ever, deletes the given element(s) and converts the remaining elements into a row vector. p = polyt(x,y,n) Finds the coecients p of the polynomial of degree n that best ts data x, y in a least squares sense. The coecients are given from the highest order term to the lowest. polyval(p,x) Returns the value of the polynomial with coecients p evaluated at x. Graphics Commands Most graphics editing can also be done using the Graphics Editor in each gure window, but for commands you will be running repeated, inclusion in scripts, etc., it is easier to specify them in the commands. The basics are pretty self-explanatory, but most of the commands have further options you can nd in the Help documentation. plot(x1, y1, x2, y2) Plots x1 versus y1 and x2 versus y2 on a single gure area(x,y) Plots x versus y, but lls in the area under the curve. Useful if your gure is trying to be a cross section. hold on/hold o Holds the current gure so that subsequent graphing com- mands are added to it, rather than creating a new gure. Useful when 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. Dont forget the around the label. ylabel(label (units)) Labels the x axis. Dont forget the around the label. title(Plot Title) Titles the plot. Dont forget the around the title. axis([xmin xmax ymin max]) Adjusts the axes after plotting. 3 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 species: 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 specied 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 with no line. There are also more advanced options which let you specify a wider range of colours, control the colour of line and and marker separately, change the thickness of the line and size of the marker, etc. These usually 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 a wider range of colours, you have to use RGB triplets (in the range 01, so if youre used to giving them out of 255, write them as fractions [55/255 100/255 190/255], etc. RGB triplets (red-green-blue) are a common way of specifying colours in computing, and there are charts of colours and their triplets available online (e.g. Wikipedia Web Colours article). Conditional Statements and Loops If youve done a bit of programming, these will be familiar to you, and its only MATLABs particular syntax that you need to learn. If you havent done programming before, these are statements that enable you to write code that will be executed only under certain conditions, e.g. if x < 10 or code that 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 the logical operators & (logical AND), | (logical OR), and (logical NOT). Note that when testing for equality, 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 the single forms do not). Sample expressions: x < 10 & y == 4 x is less than 10 and y equals 4 x + 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 Conditional Statements The basic conditional statement is: if (logical expression) (code to evaluate if ex- pression is true) end e.g. if x < 10 b = 2 x end which says If x is less than 10, set b equal to 2 x . If x is greater than or equal to 10, b wont be assigned any value (or will retain the value it had before the if statement started. To evaluate dierent 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 rst expression is true, the rst batch of code is evaluated, and the programme leaves the if block of code. If the rst expression is false, it tries the second expression, and so on. Only one batch of code is ever evaluated. You can have as many elsif statements as you need, and you do not have to have an else statement if no code is to be evaluated when all expressions are false. These statements can also be nested - you can put another if statement in the code to be evaluated if a given expression is true, i.e. if x < 10 if y < 10 b = x y else b = x + y else b = x end Note that this is not a particularly sensible set of statements... If you have dierent code to be evaluated when an expression is equal to certain values, i.e. you are continually testing if x == number, there is a very similar structure called switch that you can (and probably should) use instead. Loops Loops are for when you want to execute a statement a set number of times or for as long as some expression is true. The for statement is used to evaluate code a set number of times, for example as 5 x goes from 1 to 20: for (range of values) (code to evaluate for each value) end e.g. b = 0 for x = 1 : 20 b = b + x 2 end which Finds the sum of the square from 1 to 20. The b = 0 ensures that any pre- vious value of b doesnt 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 while expression is true) end e.g. x = 1 while x < 2000 x = 2x end which Prints the powers of 2 that are less than 2000. The x = 1 starts the process o correctly. It is important to make sure that loops will eventually exit. This is particularly important with while loops. If, for example, you forget to write the statement that changes the value of x you will be testing the same condition ad innitem (e.g. 1 < 10, which is always and forever true), and the loop becomes an innite loop. If your code mysteriously seems to run forever and ever, check for innite loops. 6