MATLAB Quick Reference

Similar documents
Introduction to MATLAB

Chapter 1 Introduction to MATLAB

MATLAB Tutorial. Digital Signal Processing. Course Details. Topics. MATLAB Environment. Introduction. Digital Signal Processing (DSP)

Lecturer: Keyvan Dehmamy

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

Mechanical Engineering Department Second Year (2015)

Quick MATLAB Syntax Guide

Part V Appendices c Copyright, Todd Young and Martin Mohlenkamp, Department of Mathematics, Ohio University, 2017

Programming in Mathematics. Mili I. Shah

Introduction to PartSim and Matlab

Some elements for Matlab programming

LAB 1 General MATLAB Information 1

Introduction to MATLAB

Programming in MATLAB

PART 1 PROGRAMMING WITH MATHLAB

Introduction to Matlab

Introduction to MATLAB

Experiment 1: Introduction to MATLAB I. Introduction. 1.1 Objectives and Expectations: 1.2 What is MATLAB?

Introduction to MatLab. Introduction to MatLab K. Craig 1

workspace list the variables and describe their matrix sizes 4x1 matrix (4 rows, 1 column) x=[3.4, 7, 2.2] 1x3 matrix (1 row, 3 columns)

Introduction to MATLAB 7 for Engineers

Introduction to Engineering gii

Introduction to MATLAB

A General Introduction to Matlab

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

Consider this m file that creates a file that you can load data into called rain.txt

Welcome to EGR 106 Foundations of Engineering II

Introduction to MATLAB. Computational Probability and Statistics CIS 2033 Section 003

MATLAB Tutorial EE351M DSP. Created: Thursday Jan 25, 2007 Rayyan Jaber. Modified by: Kitaek Bae. Outline

This is a basic tutorial for the MATLAB program which is a high-performance language for technical computing for platforms:

MATLAB. A Tutorial By. Masood Ejaz

Interactive Computing with Matlab. Gerald W. Recktenwald Department of Mechanical Engineering Portland State University

To start using Matlab, you only need be concerned with the command window for now.

Inlichtingenblad, matlab- en simulink handleiding en practicumopgaven IWS

Introduction to Matlab

Basic MATLAB Tutorial

1 Introduction to Matlab

What is Matlab? The command line Variables Operators Functions

Starting Matlab. MATLAB Laboratory 09/09/10 Lecture. Command Window. Drives/Directories. Go to.

A very brief Matlab introduction

Lab 1 - Worksheet Spring 2013

1.1 ABOUT MATLAB and MATLAB GUI (Graphical User Interface)

MATLAB Introduction to MATLAB Programming

Matlab Programming Introduction 1 2

MATLAB QUICK START TUTORIAL

ELEN E3084: Signals and Systems Lab Lab II: Introduction to Matlab (Part II) and Elementary Signals

Introduction to MATLAB for Numerical Analysis and Mathematical Modeling. Selis Önel, PhD

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

General MATLAB Information 1

A QUICK INTRODUCTION TO MATLAB

QUICK INTRODUCTION TO MATLAB PART I

Introduction to MATLAB Practical 1

MATLAB Tutorial. Mohammad Motamed 1. August 28, generates a 3 3 matrix.

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

A QUICK INTRODUCTION TO MATLAB. Intro to matlab getting started

Prof. Manoochehr Shirzaei. RaTlab.asu.edu

INTRODUCTION TO MATLAB

MATLAB NOTES. Matlab designed for numerical computing. Strongly oriented towards use of arrays, one and two dimensional.

MATLAB Fundamentals. Berlin Chen Department of Computer Science & Information Engineering National Taiwan Normal University

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An

Chapter 2. MATLAB Fundamentals

Chapter 3 Functions and Files

Due date for the report is 23 May 2007

Finding, Starting and Using Matlab

What is a Function? EF102 - Spring, A&S Lecture 4 Matlab Functions

Introduction to MATLAB 7 for Engineers

Introduction to Matlab

Getting started with MATLAB

12 whereas if I terminate the expression with a semicolon, the printed output is suppressed.

Programming 1. Script files. help cd Example:

EP375 Computational Physics

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

INTRODUCTION TO MATLAB PLOTTING WITH MATLAB

A Guide to Using Some Basic MATLAB Functions

User Guide.

Introduction to Matlab. Summer School CEA-EDF-INRIA 2011 of Numerical Analysis

Table of Contents. Basis CEMTool 7 Tutorial

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

MATH (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab

Chapter 3. built in functions help feature elementary math functions data analysis functions random number functions computational limits

Starting MATLAB To logon onto a Temple workstation at the Tech Center, follow the directions below.

Digital Image Analysis and Processing CPE

PowerPoints organized by Dr. Michael R. Gustafson II, Duke University

Introduction to MATLAB for Engineers, Third Edition

Introduction to MATLAB for Engineers, Third Edition

MATLAB Workshop Dr. M. T. Mustafa Department of Mathematical Sciences. Introductory remarks

Getting Started. Chapter 1. How to Get Matlab. 1.1 Before We Begin Matlab to Accompany Lay s Linear Algebra Text

Introduction to GNU-Octave

MATLAB Tutorial. 1. The MATLAB Windows. 2. The Command Windows. 3. Simple scalar or number operations

Chapter 1 MATLAB Preliminaries

MATELECT PDsoft v1.00

Fundamentals of MATLAB Usage

TECH TIP VISION Calibration and Data Acquisition Software

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

Introduction to Matlab

EE168 Handout #6 Winter Useful MATLAB Tips

A Quick Tutorial on MATLAB. Zeeshan Ali

Introduction to MATLAB. Dr./ Ahmed Nagib Elmekawy Mechanical Engineering department, Alexandria university, Egypt Spring 2017.

MATLAB BEGINNER S GUIDE

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

Transcription:

MATLAB Quick Reference Operators Matrix Operations Array or Element by Element + Addition - Subtraction * Matrix Multiplication.* Element by Element Multiplication / Right Matrix Division b/ A=bA 1./ Element by Element Right Division \ Left Matrix Division A b=a 1 b.\ Element by Element Left Division A. B=B./ A ^ Raise Matrix to a power.^ Raise each Element to a power ' Transpose matrix (conjugate if complex) A'.' Transpose matrix (no complex conjugation) A.' Relational Operators Logical Operators < Less Than & And <= Less Than or Equal Or > Greater Than ~ NOT >= Greater Than or Equal == Equal ~= Not Equal Special Number Symbols pi π i 1 inf j 1 NaN Not a number ie 0/0 1

Entering Matrices x = [ 1 2 3; 4 5 6; 7 8 9] x = [ 1,2,3 4,5,6 7,8,9 ] Comma or space between elements. Semicolon or return for new row. Enclosed in square brackets. a = [ exp(0) sqrt(4) 1+2 ] Each element can be an expression. C = [ A B] C = [ A ; B] Indexing Vector Indexing variable(v) Examples V is a vector of indexes A(3) The third element in vector A. A and B are matrices with the same number of rows. A([3 8 11]) The third, eighth and eleventh elements of A. A(3:11) The third to eleventh elements of A. A(11:) A and B are matrices with the same number of columns. All elements from the eleventh to the last element Matrix Indexing variable(r,c) R is a vector of rows and C a vector of Columns Examples M(2,3) The element in the second row and third column of M. M(2, [3 8 11]) M(4,3:11) M(11:,2) M(5,:) M(11:,:) Second row, third, eighth and eleventh column. Forth row, third to eleventh column. Eleventh to the last row, second column. Fifth row, all columns. Output Display Format Eleventh to the last row, all columns. format short 4 decimal places format long 15 decimal places format format shorte format shorteng Same as above Scientific notation, 4 decimal places Engineering notation, 4 decimal places format longe format longeng Scientific notation, 15 decimal places Engineering notation, 15 decimal places 2

Generating Vectors <start> : <> x = 1 : 5 generates x = [ 1 2 3 4 5] <start> : <separation> : <> y = 0:5:20 generates y = [ 0 5 10 15 20] linspace(start,,n) n = number of elements linspace(0,10,5) generates [ 0 2.5 5 7.5 10] logspace(d1,d2,n) n elements logarithmically logspace(-1,2,4) generates [0.1 1 10 100] 1 spaced between 10 d 2 and 10 d. Utility Matrices zeros(n) n by n matrix where each element is zero. zeros(m,n) m by n matrix where each element is zero. zeros(a,b,c) 3 dimensional array, a by b by c. ones(m,n) m by n matrix where each element is one. rand(m,n) m by n matrix of random numbers. eye(n) n by n identity matrix. Variable Control who List all variables in memory. whos Same as above but with more information. clear Remove all variables from memory. clear <variable> Remove specified variables from memory. File Control Commands dir List contents of current directory. ls List contents of current directory. what List the Matlab files in the current directory. cd <directory> Change the current directory. type <filename> Display the contents of a text or.m file. delete <filename> Delete a file. diary <filename> Record all commands and results to a file. diary off Stop above. Help help help <function> lookfor <word> doc <function> Display help topics. Help on a particular function. Look for word in function descriptions. Full documentation on function. 3

In Built Functions Hit fx icon next to prompt for function browser. Only selected functions shown here. abs(x) The absolute value. Modulus round(x) Round to the nearest integer. sqrt(x) The square root. ceil(x) Round up. exp(x) The exponential base e. e x floor(x) Round down. log(x) The natural logarithm. log e x fix(x) Round towards zero. log10(x) The log base 10. log 10 x rem(x,b) Remainder of x divided by b. Trigonometry sin(x) sind(x) asin(x) asind(x) sinh(x) asinh(x) Sine. x in radians. Sine. x in degrees. The arcsine. The inverse of sin(x). Radians The arcsine. Degrees Hyperbolic Sine. The inverse Hyperbolic Sine. The above variations are also available for the following functions. cos(x) Cosine tan(x) Tangent cot(x) Cotangent sec(x) Secant csc(x) Cosecant Complex Numbers real(z) The real part of z. imag(z) The imaginary part of z. abs(z) The modulus of z. angle(z) The phase angle of z. conj(z) The complex conjugate of z. Matrix det(a) Determinant sqrtm(a) The matrix square root. norm(a) Norm expm(a) The matrix exponential base e. inv(a) Inverse logm(a) The matrix natural logarithm. [v,d]=eig(a) Statistics d = Eigenvalues, v = Eigenvectors max(x) Maximum median(x) Median var(x) Variance min(x) Minimum mean(x) Average std(x) Standard Deviation 4

Polynomials p = [1 2 3 4 5]; can represent the polynomial x 4 2x 3 3x 2 4x 5 y = polyval(p,x) Evaluate polynomial for each value in x. roots(p) p = poly( <roots>) p = polyfit(x,y,n) Roots of polynomial. Polynomial with given roots. Best fit of x,y data points to n th order polynomial. Saving, Exporting and Importing Data save <filename> Save all variable to the file filename.mat load <filename> save <filename> <variable> save <filename> <variable> -ascii load <filename>.<ext> Load in variables from the file filename.mat Save only the variable variable to the file filename.mat Save variable to the text file filename Load from the text file, to a variable called filename Misc x = input( 'What is x? ') [x,y] = ginput(1) pause pause(5) Ask the user for a number. Graph coordinates of a clicked on point. Wait for the user to press a key. Wait for 5 seconds! command Execute an operating system command display(a) Suppose a = 5. This would print "a = 5"; disp(a) Same as above, but with out the "a = ". fprintf Formatting %f Fixed point %5f 5 characters wide \n New line %e Exponential Notation %5.2f 2 decimal places (dp) \t Horizontal tab %g auto chooses %f or %e %-5.2f Left justify \\ Back slash %s String of Characters %+5.2f Print sign (+ or -) %% Percent character %d Integer (Whole numbers only) Examples What is printed Comment fprintf(' x = %f ',pi) x = 3.141593 No new line after fprintf(' x = %f \n',pi) x = 3.141593 Moves to a new line after fprintf(' L%6.2fR \n',pi) L 3.14R Number is 6 chars wide with 2 dp fprintf('%s L%-6.2fR','Hi',pi) Hi L3.14 R The string 'Hi', then left justify number S = sprintf(' x = %f ',pi); NOTHING S is a string containing ' x = 3.141593' 5

Graph Commands plot(y) Plot y against index number. plot(x,y) Plot y against x plot(x1,y1,x2,y2) Plot y1 against x1 and y2 against x2. plot(x,y,'r+') Plot y against x using red plus signs. plot(x1,y1,'r+',x2,y2,'go') Red plus signs for x1 and y1, Green circles for x2 y2. Symbol Line Type or Mark Symbol Colour Other Types of Plot. Point r Red fill(x,y,'r') Red filled graph o Circle g Green bar(x,y) Bar graph x X mark b Blue loglog(x,y) x & y log scale + Plus sign y Yellow semilogx(x,y) x log, y linear * Stars m Magenta semilogy(x,y) x linear, y log - Solid line c Cyan polar(theta,r) Polar plot : Dotted line w White surf(x,y,z) 3D surface -. Dash dot line k Black mesh(x,y,z) 3D mesh -- Dash Line plot3(x,y,z) 3D line plot Other Graphics Commands title('title') xlabel('x axis') ylabel('y axis') zlabel('z axis') text(x,y,'my Text') grid hold on hold off subplot(r,c,n) Graph title. Label the x-axis. Label y and z axis. Place text at coordinates x,y. Place a grid on the graph. Add any new plot to the current graph. Replace current plot with any new plot. Split figure into r rows by c columns of subplots. subplot(2,3,1) subplot(2,3,2) subplot(2,3,3) subplot(2,3,4) subplot(2,3,5) subplot(2,3,6) axis([minx maxx miny maxy]) Set the limits of the graph in X and Y. (Note 4 element vector) h = figure New graphics window. figure(h) Change to plotting in figure h. delete(h) Delete figure h. clf Clear current figure. drawnow Force the graph to update now. 6

Enumerated Loops (for) The general form of a for loop is :- Programming Examples for <variable> = <vector> A = rand(1,5); for a = A disp(a) for k = [ 1 7 3 pi i] disp(k) Precondition Loops (while) Below is the general form of a while loop. Example while(<condition>) A = 7; %Find the square root of A. x=1; %First guess err=1; %Set error to get started % Newton Raphson Iteration while(err>0.0001) x = (x.^2+a)./(2*x); % calculate the error err = abs(a-x.^2); disp(x); condition statement statement 7

Conditional Execution (if) General form of a simple if statement. If <condition> condition statement statement The form of if statement with else if <condition> <statement1> <statement2> else <statement3> <statement4> condition statement1 statement2 statement3 statement4 You can also have as many elseif parts as you like. if <condition1> <statement1> elseif <condition2> <statement2> else <statement3> Con 1 statement1 Con 2 statement2 statement3 8

Switch Execution deps on the value of a variable. switch <variable> case 1 <statement1> case 2 <statement2> case 3 <statement3> otherwise <statement4> The case values can be any value that the switch variable can take. You can also put multiple values after the case. case {1,2,3,4,5} On the right A is the switch variable. A == 1 A == 2 A == 3 statement4 statement1 statement2 statement3 Functions Function Definition function sum = myadd(a,b) % The first block of comments % defines what is printed out when % you type help myadd Using the Function s = myadd(<expression>,<expression>) % Comment not part of help sum = a + b; function [sum,diff] = add_sub(a,b) sum = a + b; diff = a - b; [s,d] = add_sub(<expression>,<expression>) 9

Unix Commands Linux and MAC OSX operating systems are both based on UNIX. File and Directory Paths /var/tmp Absolute path from root p5computing/exercise1 Relative path from current working directory.. The current directory cp /tmp/myfile... The directory above. ~ Your home directory cd../exercise2 cd../../.. cp /tmp/myfile ~ cd ~/p5computing Commands ls List the contents of the current directory. ls -a List current directory, showing hidden files. ls -l List current directory, long format. More information. ls <directory path> List the contents of the specified directory. ls -al <directory path> As above showing hidden files and long format. mkdir <directory name> Make a new directory with the given name. cd <directory path> Change the current working directory. pwd Print the current working directory. cp <file path> <new file name> Copy a file to a new file. cp <file path> <directory path> Copy a file into the specified directory. mv <file path> <new file name> Change the name of a file to a new file name. mv <file path> <directory path> Move a file into the specified directory. rm <list of files> Remove all files in the list. rm -i <list of files> Remove all files in the list, asking for confirmation. rm -R <directory path> Remove a directory and its contents. rmdir <directory path> Remove an empty directory. cat <file path> Type file to screen. more <file path> Type file to screen a page at a time. man <command> Display manual pages for the command. Wild Cards? A single character rm prog?.m Remove prog1.m, prog2.m * A character string cp *.m MatlabFiles Copy all files ing.m to a directory. 10

DOS Commands The commands you can use in a windows command prompt. File and Directory Paths Drive:<path><filename> Drive: For example For Example C:\TEMP\mydirectory\myfile.txt A: Floppy drive D: DVD C: The main hard disc. F: USB Memory Stick If omitted, use the current drive. <path> Absolute path from the root of the drive. \TEMP\mydirectory\ or the path from the current directory. p5computing\exercise2\myfunction.m If directory names contain spaces, use double quotes. Program Files\MATLAB If omitted, use current working directory.. The current working directory.. The directory above. Commands dir List the contents of the current directory. dir /w List current directory using wide format. dir <directory path> List the contents of the specified directory. mkdir <directory name> Make a new directory with the given name. cd <directory path> Change the current working directory. copy <file path> <new file name> Copy a file to a new file. ren <file path> <new file name> Rename a file to a new file name. move <file path> <directory path> Move a file into the specified directory. del <list of files> Delete all files in the list. del <list of files> /P Delete all files in the list, asking for confirmation. rmdir <directory path> Remove an empty directory. type <file path> Type file to screen. help <command> Display help on command. Wild Cards? A single character del prog?.m Remove prog1.m, prog2.m * A character string move *.xls mydir Copy all files ing.xls to a directory. Note: In windows, directories are also called folders. 11

Matlab Quick Reference, Version 2.1 Eric Peasley, Department of Engineering Science, University of Oxford 12