Chapter 2. MATLAB Basis

Similar documents
Introduction to Engineering gii

Finding, Starting and Using Matlab

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

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

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

Introduction to MATLAB

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

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

Chapter 2 (Part 2) MATLAB Basics. dr.dcd.h CS 101 /SJC 5th Edition 1

PROGRAMMING WITH MATLAB DR. AHMET AKBULUT

Digital Image Analysis and Processing CPE

Chapter 1 Introduction to MATLAB

Programming in Mathematics. Mili I. Shah

EP375 Computational Physics

Introduction to MATLAB

9/4/2018. Chapter 2 (Part 1) MATLAB Basics. Arrays. Arrays 2. Arrays 3. Variables 2. Variables

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

Quick MATLAB Syntax Guide

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

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

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

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

Part #1. A0B17MTB Matlab. Miloslav Čapek Filip Kozák, Viktor Adler, Pavel Valtr

Introduction to MATLAB

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

CME 192: Introduction to Matlab

1 Week 1: Basics of scientific programming I

ENGR 1181 Autumn 2015 Final Exam Study Guide and Practice Problems

Introduction to MatLab. Introduction to MatLab K. Craig 1

ENGR 1181c Midterm Exam 2: Study Guide and Practice Problems

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

A Short Introduction to Matlab

Numerical Analysis First Term Dr. Selcuk CANKURT

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

MATLAB QUICK START TUTORIAL

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Introduction to Matlab

Lecture 2 Introduction to MATLAB. Dr.Tony Cahill

2.0 MATLAB Fundamentals

PART 1 PROGRAMMING WITH MATHLAB

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

Dr Richard Greenaway

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

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

What is Matlab? The command line Variables Operators Functions

Lecturer: Keyvan Dehmamy

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

Lab 1 - Worksheet Spring 2013

Laboratory 1 Octave Tutorial

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

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

MATLAB Constants, Variables & Expression. 9/12/2015 By: Nafees Ahmed

Matlab as a calculator

Welcome to EGR 106 Foundations of Engineering II

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

Introduction to Scientific and Engineering Computing, BIL108E. Karaman

Introduction to MATLAB

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

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

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

AMS 27L LAB #1 Winter 2009

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

Introduction to MATLAB for Engineers, Third Edition

Matlab Programming Introduction 1 2

ENGR 1181 Midterm Exam 2: Study Guide and Practice Problems

Introduction to Computer Programming with MATLAB Matlab Fundamentals. Selis Önel, PhD

Basic MATLAB Tutorial

A QUICK INTRODUCTION TO MATLAB

Introduction to Matlab

Introduction to MATLAB

1 Introduction to MATLAB

Arithmetic operations

A QUICK INTRODUCTION TO MATLAB. Intro to matlab getting started

Introduction to MATLAB Programming

Chapter 2. Outline. Simple C++ Programs

Programming 1. Script files. help cd Example:

MATLAB. MATLAB Review. MATLAB Basics: Variables. MATLAB Basics: Variables. MATLAB Basics: Subarrays. MATLAB Basics: Subarrays

Chapter 2 MATLAB Basics

Lecture 1: What is MATLAB?

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

1 Introduction to MATLAB

Dr Richard Greenaway

MATLAB: The Basics. Dmitry Adamskiy 9 November 2011

Matrix Manipula;on with MatLab

Maths Functions User Manual

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

Programming in MATLAB

Chapter 4: Basic C Operators

QUICK INTRODUCTION TO MATLAB PART I

Introductory MATLAB. Appendix A A.1 BACKGROUND A.2 STARTING WITH MATLAB. Core Topics

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

MATLAB Programming for Numerical Computation Dr. Niket Kaisare Department Of Chemical Engineering Indian Institute of Technology, Madras

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

MATLAB Introduction to MATLAB Programming

Matlab Workshop I. Niloufer Mackey and Lixin Shen

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

Introduction to PartSim and Matlab

A Guide to Using Some Basic MATLAB Functions

ANSI C Programming Simple Programs

Course Layout. Go to follow instr. Accessible within campus (only for the first download)

Transcription:

Chapter MATLAB Basis Learning Objectives:. Write simple program modules to implement single numerical methods and algorithms. Use variables, operators, and control structures to implement simple sequential algorithms Topics/Outline:. Arrays. Load and Save. Disp and fprintf..m-files 5. Plotting Chapter M: MATLAB Basis

Variables and Arrays The fundamental unit of data in MATLAB program is the array (Vector or Matrix) Even single value variables (Scalars) All operations are optimized for vector use Loops run slower in MATLAB than in Fortran (not a vector operation) size command gives size of the matrix Scalars, Vectors, Matrices MATLAB treat variables as arrays (matrices) Matrix (m n) - a set of numbers arranged in rows (m) and columns (n) Scalar: matrix Row Vector: n matrix Column Vector: m matrix A 5. 7 B 5.. 7. 5. C B'. 7. D. 5. 7. 5 9. 5 Chapter M: MATLAB Basis

Array: Data Organized into rows and columns Row Row Row A(,5) Row Col Col Col Col Col 5 Col 6 MATLAB Arrays Arrays fundamental unit of data 5. A 5. 5 5 matrix A = [,,-.5,,;,,.5,-,5]; Optional, use if it helps readability (comma) Start new row (semicolon) Suppress display (semicolon) Chapter M: MATLAB Basis

Data types All numbers are double precision The numerical values can be real, imaginary (i or j), or complex Text is stored as arrays of characters You don t have to declare the type of data (defined when running) MATLAB is case-sensitive!!! var = -.; var = i; var = -j; var =.5+.i; var5 = sqrt(.5); string = This is a character string String = Please enter your NetID Variable Names Usually, the name is identified with the problem Variable names may consist of up to 6 characters Variable names may be alphabetic, digits, and the underscore character ( _ ) Variable names must start with a letter ABC, A, C56, CVEN_, email_address day, year, iteration, max time, velocity, distance, area, density, pressure Time, TIME, time (case sensitive!!) Chapter M: MATLAB Basis

Initializing Variables Explicitly list the values reads from a data file uses the colon (:) operator reads from the keyboard A = [; ; 5; ]; B = [ 5; -6 -] C = [ 5 ; (continuation) -; 5 -] E = [A; ; A]; F = [C(,); A] Matrix Concatenation z x u v ; y 7 9 x y 7 9 x ; y 7 9 x y ; y x 7 7 9 9 Chapter M: MATLAB Basis 5

Chapter M: MATLAB Basis 6 E 5 C Colon Operator Creating new matrices (extracting subarrays) from an existing matrix C = [,,5; -,,;,,-;,,] E = C(:,:) = [- ; -] Colon Operator Creating new matrices from an existing matrix C = [,,5; -,,;,,-;,,] G 5 C G = C(:,:) = [,;,]

The end Function In array operations, end returns the highest value of a subscript C = [ 5; - ; -; ] H = C(:end,:end) = [ ; ] C 5 H Colon Operator Use subarrays on the LHS of a matrix Update elements of the existing array C = [ 5; - ; -; ] C([ ],:) = [ ; 5 6] C 5 C 5 6 Chapter M: MATLAB Basis 7

Chapter M: MATLAB Basis 8 Colon Operator Variable_name = first:incr:last time =.:.5:.5 time = [.,.5,.,.5,.,.5] values = :-: values = [, 9, 8, 7, 6, 5,,, ] linspace gives evenly spaced values x = linspace(,5); y = linspace(-pi,pi) x = linspace(a,b,n_pts) Special Matrices ones(,) ones() zeros(,) eye() Built-in MATLAB functions: zeros, ones, eye

Multidimensional Arrays» A(:,:,)=[ -5 7; 9 -];» A(:,:,)=[- 6; - 6];» A A(:,:,) = -5 7 9 - A(:,:,) = - 6-6» whos A Name Size Bytes Class A xx 96 double array Grand total is elements using 96 bytes MATLAB allocates array elements in column major order. A(,,),A(,,),A(,,),A(,,),A(,,),A(,,), A(,,),A(,,),A(,,),A(,,),A(,,),A(,,) Predefined Special Values The predefined values may be used any time in MATLAB without initializing them first Function Purpose pi (=.596558979) i, j (imaginary part of a complex number) Inf Machine infinity (divided by ) NaN Not-a-Number. Undefined mathematical operation. clock (year, month, day, hour, minute, second) date day-month-year, such as -Jan- eps epsilon, smallest difference between two numbers that can be represented on the computer ans store the result of unassigned variables Chapter M: MATLAB Basis 9

>> pi ans =.6 >> size(pi) ans = >> a=[ ; 5 6] a = 5 6 >> size(a) ans = pi.6 a= a 5 6 MATLAB Example» x=+5-. x = 7.8» y=*x^+5 y = 87.5» z=x*sqrt(y) z = 6.86» A=[ ; 5 6] A = 5 6» b=[;;5] b = 5» C=A*b C = 5» who Your variables are: A b y C x z» whos Name Size Bytes Class A x 8 double array C x 6 double array b x double array x x 8 double array y x 8 double array z x 8 double array» save Saving to: matlab.mat» save matrix default filename filename matrix Chapter M: MATLAB Basis

Initializing Variables with Keypad Input It is possible to prompt a user and initialize a variable with data input at the keyboard Name = input( Enter your name:, s ) SID = input( Enter your student ID: ) Tel = input( Telephone number: ) Cell = input( Cell phone number: ) Email = input( Email address:, s ) Input may be a value or a character string Array Operations An array operation is performed element-by-element C() A()* B(); C() A()* B(); C() A()* B(); C() A()* B(); C(5) A(5)* B(5); MATLAB: C = A.*B; Dot-operator works for.*,./,.^ Not needed for +, - Chapter M: MATLAB Basis

Element-by-Element Operations Symbol Operation Form Example Scalar-array addition AB [, 6] [ 7, 9] Scalar-array subtraction AB [ 8, ] 6 [, ] Array addition AB [, 6] [ 8, ] [, 9] Array subtraction AB [, 6] [ 8, ] [, ].* Array multiplication A.* B [, 6].*[, ] [ 6, 8]./ Array right division A. / B [, 7]. / [ 8, 5] [ / 8, 7 / 5].\ Array left division A.\ B [, 7]. \ [ 8, 5] [ \ 8, 7 \ 5].^ Array exponentiation A.^ B [, ].^ [ ^, ^ ] [ 6, 8].^[, 5] [ ^, ^ 5] [ 9, ] [ 5, ].^[, ] [ 5 ^, ^ ] [ 5, 8] Hierarchy of Arithmetic Operations. Parentheses, starting with the innermost pair. Exponentiation, from left to right. Multiplication and division with equal precedence, from left to right. Addition and subtraction with equal precedence, from left to right >> distance =.5 * accel * time^ >> distance =.5 * accel *(time^) >> distance = (.5 * accel * time)^ distance = distance distance Chapter M: MATLAB Basis

Chapter M: MATLAB Basis But a*b gives an error (undefined) because dimensions are incorrect. Need to use.* Vector and Matrix operations 7 b a 6 b 5 a 5* 6 * * a.* b Vectorized Matrix Operations 9 8 ).^ B ( F 5 7 8 A.^ E.5.6.75 B / A. D B A.* C 5 B 8 A

Array Operations for m n Matrices A : ; - : - : -; - 5 B A.* 5 5 5 5 8 C A.^ 8 7 5 5 7 7 8 5 6 6 Matrix Multiplications Recall how matrix multiplication works a d b e g c h f i j ag bh ci k dg eh fi l aj bk cl dj ek fl g h i j a k d l b e ga jd c ha kd f ia ld gb je hb ke ib le gc jf hc kf ic lf [A]*[B] [B]*[A] Chapter M: MATLAB Basis

Matrix Multiplication Matrix multiplication can be performed only if the inner dimensions are equal MATLAB In Fortran, the matrix multiplication has to be done by Do Loops In MATLAB, it is automatic A*B = C Note no period (not element-by-element operation) For vectors A*x = b Chapter M: MATLAB Basis 5

Chapter M: MATLAB Basis 6 Matrix Transpose ) ( )( ) ( ) )( ( - y' x * 6 9 6 8 x'* y - y' ; x' y ; x Built-in Functions Use help elfun for a list of elementary math functions All the standard operators +, -, *, /, ^ sin, cos, exp, tanh, log, log, etc. These operators are vectorized exp() exp(5) exp() exp(a) ; sin() sin(5) sin() sin( a ) ; 5 a

Common MATLAB Built-in Mathematical Functions abs(x) sin(x), cos(x), tan(x) asin(x), acos(x), atan(x), atan(y,x) angle(x) phase angle of complex x exp(x) sqrt(x) log(x), log(x) mod(x,y) remainder or modulo function [value,index] = max(x) [value,index] = min(x) Common MATLAB Built-in Rounding Functions ceil(x) rounds x to the nearest integer towards + fix(x) rounds x to the nearest integer towards floor(x) rounds x to the nearest integer towards round(x) rounds x to the nearest integer ceil(7.6) = 8, ceil(-7.6) = -7 fix(7.6) = 7, fix(-7.6) = -7 floor(7.6) = 7, floor(-7.6) = -8 round(7,6) = 7, round(-7.6) = -7 Chapter M: MATLAB Basis 7

Common MATLAB Built-in String Conversion Functions char(x) convert a matrix of numbers into a character string double(x) convert a character string into a matrix of numbers intstr(x) covert x into an integer character string numstr(x) convert x into a character string strnum(x) converts character sting s into a numeric array» string = 'Texas'; double(string) ans = 8 97 5» x=[8 97 5]; char(x) ans = Texas» intstr('tamu Civil') ans = 8 65 77 85 67 5 8 5 8 See Table in Appendix A for ASCII character set MAT Files Data Files memory efficient binary format preferable for internal use by MATLAB program ASCII files in ASCII characters useful if the data is to be shared (imported or exported to other programs) ASCII American Standard Code for Information Interchange Chapter M: MATLAB Basis 8

MATLAB Input To read files in if the file is an ascii table, use load if the file is ascii but not a table, file I/O needs fopen and fclose Reading in data from file using fopen depends on type of data (binary or text) Default data type is binary Save Files 8-digit text format (variable list) save <fname> <vlist> -ascii 6-digit text format save <fname> <vlist> -ascii -double Delimit elements with tabs save <fname> <vlist> -ascii -double -tabs Example: Vel = [ 5; -6 -] save velocity.dat Vel -ascii.e+.e+ 5.e+ -6.e+.e+ -.e+ Chapter M: MATLAB Basis 9

Load Files Read velocity into a matrix velocity.dat >> load velocity.dat >> velocity velocity = 5-6 -.e+.e+ 5.e+ -6.e+.e+ -.e+ Load Files Create an ASCII file temperature.dat % Time Temperature. 75..5 7.. 7.6.5 7.8. 79..5 8. read Time and Temperature from temp.dat >> load temperature.dat >> temperature Note: temperature is a 6 matrix Chapter M: MATLAB Basis

MATLAB Output Matlab automatically prints the results of any calculation (unless suppressed by semicolon ;) Use disp to print out text to screen disp (x.*y) disp ( Temperature = ) sprintf - display combination Make a string to print to the screen output = sprintf( Pi is equal to %f, pi) MATLAB Output numstr: convert a number to a string intstr: convert an integer to a string (round the element to integer)» string = ['The value of Pi = ' numstr(pi)];» disp (string) The value of Pi =.6» string = ['Value of sqrt(.5) ~ ' intstr(sqrt(.5))];» disp (string) Value of sqrt(.5) ~ Chapter M: MATLAB Basis

Formatted Output fprintf (format-string, var,.) %[flags] [width] [.precision] type Examples of type fields %d display value as an integer %e display in exponential format %f display in floating point or decimal notation %g display using %e or %f, depending on which is shorter %% display % \n skip to a new line Numeric Display Format MATLAB Command Display Example format short default.6 format long decimals.596558979 format bank decimals. format short e decimals.6e format long e 5 decimals.596558979e format,,blank x = [5 - -]; format + x = [+ - + + -] (+/- sign only) (blank for ) Chapter M: MATLAB Basis

fprintf( ) of Scalar temp = 98.6; fprintf( The temperature is %8.f degrees F.\n, temp); The temperature is 98.6 degrees F. fprintf( The temperature is %8.f degrees F.\n, temp); The temperature is 98.6 degrees F. fprintf( The temperature is %8.e degrees F.\n, temp); The temperature is 9.86e+ degrees F. fprintf( ) of Scalar speed =.; fprintf( The speed is %8.f m/s. \n, speed); Save at least 8 characters with decimal digits The speed is. m/s. speed = 59.5; fprintf( The speed is %6.f cm/s. \n, speed); Save at least 6 characters with decimal digits The speed is 59. cm/s. Chapter M: MATLAB Basis

fprintf( ) of Matrices score = [ ; 75 88 9; 99 8 95 5] fprintf( Game %d score: Houston: %d Dallas: %d \n, score) Game score: Houston: 75 Dallas: 99 Game score: Houston: 88 Dallas: 8 Game score: Houston: Dallas: 95 Game score: Houston: 9 Dallas: 5 M-Files You can create and save code in text files using MATLAB Editor/Debugger or other text editors (called m-files since the ending must be.m) Use % to add comments These files are called programs. They are similar to FORTRAN or C source codes. A script can be executed by typing the file name, or using the run command MATLAB executes everything stored in a.m file one line after the other as if the commands were entered in the command window Chapter M: MATLAB Basis