MATLAB Basics L M Kalnins, February 2010

Similar documents
The Center for Teaching, Learning, & Technology

Create a Poster Using Publisher

Beginner s Matlab Tutorial

This activity will show you how to draw graphs of algebraic functions in Excel.

Ohio University Computer Services Center August, 2002 Crystal Reports Introduction Quick Reference Guide

Lecture 2 Mathcad Basics

Statgraphics Getting started

LESSON 7: IMPORTING AND VECTORIZING A BITMAP IMAGE

Excel 2007 Basic knowledge

Excel -- Creating Charts

Advanced Programming with LEGO NXT MindStorms

Plotting: Customizing the Graph

CATIA Basic Concepts TABLE OF CONTENTS

Ofgem Carbon Savings Community Obligation (CSCO) Eligibility System

Excel 2003 A Beginners Guide

Excel Tutorial. Bio 150B Excel Tutorial 1

MATLAB Functions. function [Out_1,Out_2,,Out_N] = function_name(in_1,in_2,,in_m)

MATLAB Basics MATLAB numbers and numeric formats

Excel 2007 A Beginners Guide

Introduction to MS WINDOWS XP

Introduction To Microsoft Office PowerPoint Bob Booth July 2008 AP-PPT5

CMS Training Manual. A brief overview of your website s content management system (CMS) with screenshots. CMS Manual

AMATH 352 Lecture 3 MATLAB Tutorial Starting MATLAB Entering Variables

DataPA OpenAnalytics End User Training

Tutorial for Tracker and Supporting Software By David Chandler

Curve Fitting, Loglog Plots, and Semilog Plots 1

Chapter 1. Creating Sketches in. the Sketch Mode-I. Evaluation chapter. Logon to for more details. Learning Objectives

DOING MORE WITH WORD: MICROSOFT OFFICE 2010

There are six different windows that can be opened when using SPSS. The following will give a description of each of them.

Microsoft PowerPoint Exercises 4

How to test and debug an ASP.NET application

If you know exactly how you want your business forms to look and don t mind

Jump-Start Tutorial For ProcessModel

MatLab Basics. Now, press return to see what Matlab has stored as your variable x. You should see:

Excel Level Two. Introduction. Contents. Exploring Formulas. Entering Formulas

Virtual Heart User Manual Username Password

Publisher 2010 Cheat Sheet

MICROSOFT ACCESS STEP BY STEP GUIDE

Excel 2003: Ringtones Task

Migrating to Excel 2010 from Excel Excel - Microsoft Office 1 of 1

This activity will guide you to create formulas and use some of the built-in math functions in EXCEL.

Business Objects 4.1 Quick User Guide

Getting Started with R and RStudio 1

WebEx Sharing Resources

Microsoft Excel 2010 Tutorial

Editing your Website User Guide

Intro to Excel spreadsheets

Formulas, Functions and Charts

5. Tutorial. Starting FlashCut CNC

Windows XP Pro: Basics 1

Apple Mac Fundamentals: A Tutorial. Updated 24/4/2013 By Mac Thing enquiries@macthing.co.uk Table of Contents:

Virtual Private Server Manual

Microsoft PowerPoint 2010 Handout

Microsoft Word 2013 Tutorial

Switching from PC SAS to SAS Enterprise Guide Zhengxin (Cindy) Yang, inventiv Health Clinical, Princeton, NJ

Adobe Illustrator CS5 Part 1: Introduction to Illustrator

Getting Started with the Cadence Software

TUTORIAL 4 Building a Navigation Bar with Fireworks

Select the Crow s Foot entity relationship diagram (ERD) option. Create the entities and define their components.

Years after US Student to Teacher Ratio

SQL Server 2005: Report Builder

Euler s Method and Functions

Metatrader 4 Tutorial

Microsoft Excel 2013 Tutorial

AutoDWG DWGSee DWG Viewer. DWGSee User Guide

Hypercosm. Studio.

Content Author's Reference and Cookbook

Introduction to Microsoft Excel 2010

FIRST STEPS WITH SCILAB

Unified Communications Using Microsoft Office Live Meeting 2007

Excel 2007: Basics Learning Guide

Gestation Period as a function of Lifespan

File by OCR Manual. Updated December 9, 2008

SharePoint 2007 Get started User Guide. Team Sites

Action settings and interactivity

Introduction. Chapter 1

WORDPAD TUTORIAL WINDOWS 7

TakeMySelfie ios App Documentation

HOW TO ORGANIZE PICTURES

Intermediate PowerPoint

ECDL. European Computer Driving Licence. Spreadsheet Software BCS ITQ Level 2. Syllabus Version 5.0

Creating and Updating Your Weebly Website

Microsoft Excel Tutorial

GeoGebra Statistics and Probability

Jadu Content Management Systems Web Publishing Guide. Table of Contents (click on chapter titles to navigate to a specific chapter)

Using Microsoft Word. Working With Objects

CSC 120: Computer Science for the Sciences (R section)

Frog VLE Update. Latest Features and Enhancements. September 2014

Microsoft Migrating to Word 2010 from Word 2003

How To Use An Apple Macbook With A Dock On Itunes Macbook V.Xo (Mac) And The Powerbar On A Pc Or Macbook (Apple) With A Powerbar (Apple Mac) On A Macbook

PowerPoint 2007 Basics Website:

Computer Training Centre University College Cork. Excel 2013 Level 1

Sendspace Wizard Desktop Tool Step-By-Step Guide

Introduction to the TI-Nspire CX

Microsoft Excel 2010 Charts and Graphs

Task Card #2 SMART Board: Notebook

Basic Excel Handbook

WebSphere Business Monitor V7.0 Business space dashboards

Summary of important mathematical operations and formulas (from first tutorial):

Updates to Graphing with Excel

Transcription:

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 deping 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. reference or to copy and paste commands. Can be used for 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 checking 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 figures in separate windows, which includes the ability to fine-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 figures can also 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 later and 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 anything 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 specific queries (e.g. interpolating values, polynomial fit, etc.). The see also at the of each file is very useful if you haven t 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 file for that command. Basic Commands and Formatting pi, i, 2e6, Inf 3.14159..., 1, 2 10 6, Infinity +, -, *, / (not \) matrix addition, subtraction, multiplication, and division +, -,.*,./ (not.\) element-by-element addition, subtraction, multiplication, and division xˆn x n ( ) Used to clarify expressions and specify order of operations when necessary 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), e x, natural log of x (base 10 log is log10(x)), x, x, sine of x (in radians). sqrt(x), abs(x), sin(x) Use the Help window to find virtually any mathematical function you can think of. variable = commands ans command; Assign a value or array to a variable name. The default variable MATLAB assigns output to if you don t specify a variable. Adding a ; to the of a command prevents the output from being printed onscreen, especially useful for long arrays or repetitive calculations. function(arg1, strarg ) Enclose function arguments with () and separate with commas. Arguments 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) 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 assigning a value to an element that doesn t 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 don 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, specifies the last row or column. myarray(:,2) = [ ] Deletes the 2nd column of myarray. Deleting a single element produces an error, since the result isn t a matrix. Using only a single index, however, deletes the given element(s) and converts the remaining elements into a row vector. p = polyfit(x,y,n) Finds the coefficients p of the polynomial of degree n that best fits data x, y in a least squares sense. The coefficients are given from the highest order 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 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 find in the Help documentation. plot(x1, y1, x2, y2) Plots x1 versus y1 and x2 versus y2 on a single figure area(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 commands are added to it, rather than creating a new figure. 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. 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

You can customise the plots almost anyway you like, but the most basic options go in a single paramater, 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 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 0 1, so if you re 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 you ve done a bit of programming, these will be familiar to you, and it s only MATLAB s particular syntax that you need to learn. If you haven t 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 expression e.g. if x < 10 b = 2 x which says To evaluate different code for each of several possible alternatives, we have: If x is less than 10, set b equal to 2 x. If x is greater than or equal to 10, b won t be assigned any value (or will retain the value it had before the if statement started. if (logical expression) (code to evaluate if expression elsif (2nd logical expression) (code to evaluate if 2nd expression Here, if the first expression is true, the first batch of code is evaluated, and the programme leaves the if block of code. If the first 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.. else (code to evaluate if no expression 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 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 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) e.g. b = 0 for x = 1 : 20 b = b + x 2 which Finds the sum of the square from 1 to 20. The b = 0 ensures that any previous value of b doesn t affect 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 e.g. x = 1 while x < 2000 x = 2x which Prints the powers of 2 that are less than 2000. The x = 1 starts the process off 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 infinitem (e.g. 1 < 10, which is always and forever true), and the loop becomes an infinite loop. If your code mysteriously seems to run forever and ever, check for infinite loops. 6