QUICK INTRODUCTION TO MATLAB PART I

Similar documents
Matlab Tutorial 1: Working with variables, arrays, and plotting

MATLAB Introduction to MATLAB Programming

1 Introduction to Matlab

PART 1 PROGRAMMING WITH MATHLAB

Introduction to Matlab

Introduction to MATLAB

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

STAT 391 Handout 1 Making Plots with Matlab Mar 26, 2006

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

Mechanical Engineering Department Second Year (2015)

Chapter 2. MATLAB Fundamentals

A General Introduction to Matlab

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

Graphics and plotting techniques

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

Finding, Starting and Using Matlab

Programming in Mathematics. Mili I. Shah

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

Introduction to Matlab

LAB 1 General MATLAB Information 1

MATLAB Tutorial III Variables, Files, Advanced Plotting

Grace days can not be used for this assignment

Chapter 1 Introduction to MATLAB

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

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

DSP Laboratory (EELE 4110) Lab#1 Introduction to Matlab

What is MATLAB? It is a high-level programming language. for numerical computations for symbolic computations for scientific visualizations

Lecturer: Keyvan Dehmamy

Basic Graphs. Dmitry Adamskiy 16 November 2011

Introduction to MATLAB LAB 1

TOPIC 6 Computer application for drawing 2D Graph

Introduction to Matlab

A Guide to Using Some Basic MATLAB Functions

Introduction to MATLAB

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

What is Matlab? A software environment for interactive numerical computations

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

AMS 27L LAB #2 Winter 2009

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

Introduction to Matlab

Computer Programming in MATLAB

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

Introduction to Engineering gii

Matlab Tutorial and Exercises for COMP61021

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

Introduction to Matlab to Accompany Linear Algebra. Douglas Hundley Department of Mathematics and Statistics Whitman College

Introduction to MATLAB

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window.

Getting started with MATLAB

Introduction to MATLAB

A very brief Matlab introduction

Matlab Tutorial for COMP24111 (includes exercise 1)

Introduction to Matlab

PC-MATLAB PRIMER. This is intended as a guided tour through PCMATLAB. Type as you go and watch what happens.

PROGRAMMING WITH MATLAB WEEK 6

Matlab Tutorial. The value assigned to a variable can be checked by simply typing in the variable name:

1. Register an account on: using your Oxford address

This module aims to introduce Precalculus high school students to the basic capabilities of Matlab by using functions. Matlab will be used in

INTRODUCTION TO MATLAB PLOTTING WITH MATLAB

INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX

Some elements for Matlab programming

Additional Plot Types and Plot Formatting

Prof. Manoochehr Shirzaei. RaTlab.asu.edu

EE 301 Signals & Systems I MATLAB Tutorial with Questions

Laboratory 1 Octave Tutorial

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

Lab of COMP 406. MATLAB: Quick Start. Lab tutor : Gene Yu Zhao Mailbox: or Lab 1: 11th Sep, 2013

Chapter 3: Introduction to MATLAB Programming (4 th ed.)

Introduction to Matlab

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

Getting Started with MATLAB

Introduction to MATLAB

Graphics Example a final product:

Physics 326G Winter Class 2. In this class you will learn how to define and work with arrays or vectors.

Programming 1. Script files. help cd Example:

MATLAB SUMMARY FOR MATH2070/2970

Identity Matrix: >> eye(3) ans = Matrix of Ones: >> ones(2,3) ans =

How to learn MATLAB? Some predefined variables

CSE/NEUBEH 528 Homework 0: Introduction to Matlab

MATLAB for beginners. KiJung Yoon, 1. 1 Center for Learning and Memory, University of Texas at Austin, Austin, TX 78712, USA

Dr Richard Greenaway

Inlichtingenblad, matlab- en simulink handleiding en practicumopgaven IWS

2.0 MATLAB Fundamentals

Lab #1 Revision to MATLAB

Introduction to Matlab

OUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.

MATLAB Lesson I. Chiara Lelli. October 2, Politecnico di Milano

A QUICK INTRODUCTION TO MATLAB

General MATLAB Information 1

The Department of Engineering Science The University of Auckland Welcome to ENGGEN 131 Engineering Computation and Software Development

A QUICK INTRODUCTION TO MATLAB. Intro to matlab getting started

Introduction to MATLAB

Matlab notes Matlab is a matrix-based, high-performance language for technical computing It integrates computation, visualisation and programming usin

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

Matlab Lecture 1 - Introduction to MATLAB. Five Parts of Matlab. Entering Matrices (2) - Method 1:Direct entry. Entering Matrices (1) - Magic Square

! The MATLAB language

MATLAB Functions and Graphics

INTRODUCTION TO MATLAB

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

Transcription:

QUICK INTRODUCTION TO MATLAB PART I Department of Mathematics University of Colorado at Colorado Springs General Remarks This worksheet is designed for use with MATLAB version 6.5 or later. Once you have MATLAB running on your machine, you get MATLAB to do things for you by typing commands at the prompt sign ">>". There are various forms of help available. Typing helpwin, helpdesk, or demo opens an interactive help window help <function_name> lists the description of <function_name> in the command window diary on, diary off - record all activities on the command window into a file named "diary" (e.g. for assignments) diary <filename> - save your session in a file named "<filename>". If the file already exists, the new listing is appended. Matrices The basic object in MATLAB is a matrix (hence the name, MATtrix LABoratory). The entries of a matrix are complex numbers. There is no limitation on the size of the matrix (number of rows and number of columns). Scalars are treated as 1x1 matrices. To type a matrix into MATLAB use square brackets "[" and "]" separate elements in a row with commas "," or spaces " " use a semicolon ";" to separate rows. For example, type [1 2 3;4 5 6;7 8 9] 1 2 3 4 5 6 7 8 9 [2+3*i; pi; exp(1)]

2.0000 + 3.0000i 3.1416 2.7183 All computations are performed in double precision. The format commands switch between different output formats: format short; pi % 4 decimal digits 3.1416 format long; pi % 14 decimal digits format short e; pi % 4 decimals in exponential nonation format long e; pi % 14 decimals in exponential notation 3.14159265358979 3.1416e+000 3.141592653589793e+000 Alternatively, you can tell num2str how many digits to display num2str(pi, 3) 3.14 MATLAB has several ways to generate simple matrices (need to specify the size) zeros - matrix with all elements equal to zero ones - matrix with all elements equal to one eye identity matrix rand matrix with uniformly distributed random elements randn - matrix with normally distributed random elements Examples to try: zeros(2,3), ones(2,2), eye(3) 0 0 0 0 0 0 1 1 1 1

1 0 0 0 1 0 0 0 1 Variables Variables in Matlab are named objects that are assigned using the equal sign "=". They may contain upper and lowercase letters, any number of "_" characters and numerals, but cannot start with a numeral. names and types of variables do not have to be declared apriori. names of variables should not overlap with MATLAB keywords, function names and command names Scalar variables can be later extended into vectors and matrices Examples of valid MATLAB variable assignments: a = 1 ind = [1 3 5 7] Output_Type1 = v*q*v' name='john Smith' The following are bad choices for variable names 2for1 = 'yes' end = 1 sin = 10 i = 2 clear <variable_name> - delete the value of <variable_name> from the current working space clear all - clear values of all variables clc - clear the command window and move the cursor to the top Common Operators Semicolon ";" is used to assign a variable without getting an echo from MATLAB. Comma "," separates different commands on the same line, the result is printed for each command Colon ":" generates an ordered set of numbers Three periods " " split a long command into several lines. Comment sign "%" makes MATLAB ignore the whole line after the sign, hence is used for comments. Try the following: a = 2

b = 3; c = a+b; d = c/2; c, d who % Lists all variables defined so far whos clear % Clears all previously defined variables f = 1:5; who Arithmetic Operations "+", "-", "*", "/" conventional operators for addition, substraction, multiplication and division "\" inverse division (3\2 = 2/3 = 0.6666) "^" power operator Type the following r = 10; vol = 4*pi... *r^3/3; r,vol r = 10 vol = 4.1888e+003 ".*", "./" multiplication and division between the elements of two matrices of the same dimension ".^" power operation for each element of the matrix Try the following commands A = [1 2;3 4], B=2*ones(2) A.^2, A.*B %Note that these are not the same as A^2 and A*B A = 1 2 3 4 B = 2 2 2 2 1 4 9 16

2 4 6 8 Vectors A vector is a one-dimensional array, which is a matrix consisting of one column (column vectors) or of one row (row-vectors). MATLAB code is designed to handle matrices (in particular vectors) in an optimal way, and it contains an extensive list of operations with vectors/matrices. Let's start learing the most elementary ones. Consider the row vector x and the column vector y as follows x = [ 0, 0.5, 1, 1.5, 2], y=[0; 2; 4; 3; 1] x = y = 0 2 4 3 1 0 0.5000 1.0000 1.5000 2.0000 To access individual elements, try x(2), y(3) 0.5000 4 x(6)??? Index exceeds matrix dimensions. y(0)??? Subscript indices must either be real positive integers or logicals. x(2:4) % reduces the dimension of x by retaining only the elements ranked 2 thru 4 y(end-2:end) % reduce the dimension of y and retain only the last

three elements 0.5000 1.0000 1.5000 4 3 1 One can extract rows and columns from a given matrix. For example a = [1 2 3;4 5 6;7 8 9] a = 1 2 3 4 5 6 7 8 9 a(:,2), a(3,:) 2 5 8 7 8 9 Conversely, one can generate new matrices by concatenating old vectors/matrices: b = [a -a; a(3,:) zeros(1,3)] b = 1 2 3-1 -2-3 4 5 6-4 -5-6 7 8 9-7 -8-9 7 8 9 0 0 0 a(:)' To list all the elements of a matrix and form a row vector, type 1 4 7 2 5 8 3 6 9 Note that the listing starts with the elements on the first column, then the second and the

third! An equally-spaced vector x can be defined using the colon operator ":" x = 0:0.5:2 % (first element, step size, last element) x = 0 0.5000 1.0000 1.5000 2.0000 Another example is t = 0:.3:2*pi t = Columns 1 through 7 0 0.3000 0.6000 0.9000 1.2000 1.5000 1.8000 Columns 8 through 14 2.1000 2.4000 2.7000 3.0000 3.3000 3.6000 3.9000 Columns 15 through 21 4.2000 4.5000 4.8000 5.1000 5.4000 5.7000 6.0000 Another way to generate an equally-spaced vector is using the 'function' "linspace". x=linspace(0,0.25,5) % linspace(first element, last element, number of elements) x = 0 0.0625 0.1250 0.1875 0.2500 Pointwise multiplication, division and pointwise power: x=[1,2,3]; y=[0,2,-1]; x.*y % multiplies pointwise two vectors of the same size x./y % no loops required for accessing individual elements 0 4-3 Warning: Divide by zero. (Type "warning off MATLAB:divideByZero" to suppress this warning.) Inf 1-3 x.^2 x.^y % same as x(k)^y(k) for every k 3.^x % same as 3^x(k); the output has same size as x 1 4 9

1.0000 4.0000 0.3333 3 9 27 These operation are one of the main advantages of MATLAB, since they do not require involving loops. Basic Graphics The most efficient way of representing the outcome of a numerical computation is to plot the data. Here are a few examples of MATLAB plots. x = 0 : 0.3 : 2*pi; % low resolution y = exp(-x).*sin(2*x); plot(x,y) A better resolution is obtained below x = 0 : 0.1 : 2*pi; % higher resolution y = exp(-x).*sin(2*x); plot(x,y)

One can plot several curves at the same time plot(x,y, x,sin(x)) % The two curves appear in distinct colors; both use the same scale MATLAB offers many formatting options for such plots, e.g. x = 0 : 0.1 : 2*pi;

subplot(2,3,1); plot(x,y, x,sin(x)), axis auto subplot(2,3,2); plot(x,y, x,sin(x)), axis tight subplot(2,3,3); plot(x,y, x,sin(x)), axis tight, axis off subplot(2,3,4); plot(x,y, x,sin(x)), axis equal subplot(2,3,5); plot(x,y, x,sin(x)), axis([0 7-1 1]), grid on subplot(2,3,6); plot(x,y,'g.', x,sin(x),'ro'), axis tight, axis square The command subplot(m,n,p) divides the window into mxn regions (m rows and n columns) and chooses the pth plot for drawing into. The numbering of the regions is from left to right, then down, as you read text. There are numerous plot types for the data marks "." point "+" plus "*" star "d" diamond "o" circle "p" pentagon "s" square "^" triangle "x" x-mark Line types and line colors are, among others, "-" solid line "--" dashed line

":" dotted line "-." dash-dotted line "r" red "y" yellow "m" magenta "c" cyan "g" green "b" blue "w" white "k" black A 3D plot is obtained with the command plot3. t=0:.1:2*pi; plot3(cos(2*t), sin(2*t),t) You can rotate the 3D plot by invoking the command rotate3d Simply click the mouse button on the plot and drag. You will change in this way the viewing angle. Releasing the mouse button redraws the data. Type rotate3d again to turn off this feature. Operations with figures figure opens a new graphic window, numbered consecutively from the previous window figure(n) makes an existing graphic window (n) the current window; (all graphic commands will apply

the current window) pause holds up execution of the script until the user presses a key pause(s) holds up the execution of the script for s seconds close(n) closes the graphic window (n) close all closes all graphic windows clf clears everything inside the graphic window cla clears the plotted curves and redraws the axes figure('position',[pix,piy,pwx,pwy]) sets the size and shape of the current window o pix,piy horizontal and vertical cordinates of the left bottom corner of the window o pwx, pwy number of pixels in the width and height of the window o defalut figure('position',[232,258,560,420]) get(gcf) displays the properties of the current figure, e.g. size, location, color map, and many others set(gcf, 'PropertyName', PropertyArray) changes the property "PropertyName" of the current window according to the data in PropertyArray, e.g. set(gcf, 'DefaultTextColor', 'blue') set(gcf,'paperposition',[0.25 2.5 4 3]); hold on superposes several plots on the same graph, even if another script is executed (default is hold off) hold off recommeded to be used at the end of the script whenever hold on has been used in the script. Labels and titles xlabel('x-axis') the string 'x-axis' is printed as a label for the x-coordinate ylabel('y-axis') the string 'y-axis' is printed as a label for the y-coordinate title("the graph of y=f(x)') the string 'The graph of y=f(x)' is printed as a title of the plot legend('y=f(x)') the string 'y=f(x)' is printed In a small sub-window showing the line type or data marks text(x,y,'textbody') the string 'TextBody' is printed on the figure, starting at the absolute coordinate (x,y) pixels. Font size plot(x,y,'-', 'linewidth',3) the defalut line width is 0.5 xlabel('x-axis','fontsize',14) the default font size is 12pt