What is Matlab? A software environment for interactive numerical computations

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

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

Introduction to Matlab

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

Introduction to MATLAB

Introduction to Matlab

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

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

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

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

Logical Subscripting: This kind of subscripting can be done in one step by specifying the logical operation as the subscripting expression.

PROGRAMMING WITH MATLAB WEEK 6

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

Introduction to Matlab

A Brief Introduction to MATLAB

Eng Marine Production Management. Introduction to Matlab

Introduction to Matlab

MATLAB Guide to Fibonacci Numbers

Desktop Command window

1 Introduction to Matlab

INTRODUCTION TO MATLAB PLOTTING WITH MATLAB

Introduction to MATLAB LAB 1

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

Introduction to MATLAB

QUICK INTRODUCTION TO MATLAB PART I

A General Introduction to Matlab

GRAPHICS AND VISUALISATION WITH MATLAB

Introduction to Matlab

MAT 275 Laboratory 1 Introduction to MATLAB

How to learn MATLAB? Some predefined variables

Laboratory 1 Octave Tutorial

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

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

! The MATLAB language

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

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

MATLAB Introduction to MATLAB Programming

Lecturer: Keyvan Dehmamy

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

Mechanical Engineering Department Second Year (2015)

PART 1 PROGRAMMING WITH MATHLAB

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

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

Stokes Modelling Workshop

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

CSE 123. Plots in MATLAB

Additional Plot Types and Plot Formatting

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

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

A very brief Matlab introduction

Introduction to MatLab. Introduction to MatLab K. Craig 1

Some elements for Matlab programming

Matlab Tutorial and Exercises for COMP61021

Lab #1 Revision to MATLAB

A Guide to Using Some Basic MATLAB Functions

Prof. Manoochehr Shirzaei. RaTlab.asu.edu

Getting Started with MATLAB

Inlichtingenblad, matlab- en simulink handleiding en practicumopgaven IWS

1. Register an account on: using your Oxford address

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

Matlab Tutorial for COMP24111 (includes exercise 1)

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

Graphics in MATLAB. Responsible teacher: Anatoliy Malyarenko. November 10, Abstract. Basic Plotting Commands

AMS 27L LAB #2 Winter 2009

STAT/MATH 395 A - PROBABILITY II UW Winter Quarter Matlab Tutorial

Introduction to MATLAB

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

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

MATLAB Vocabulary. Gerald Recktenwald. Version 0.965, 25 February 2017

Dr Richard Greenaway

Introduction to MATLAB

MATLAB SUMMARY FOR MATH2070/2970

Programming in Mathematics. Mili I. Shah

Chapter 1 Introduction to MATLAB

Graphics Example a final product:

MATLAB TUTORIAL WORKSHEET

Introduction to MATLAB

GUI Alternatives. Syntax. Description. MATLAB Function Reference plot. 2-D line plot

LabVIEW MathScript Quick Reference

Introduction to Matlab

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

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

ECE 202 LAB 3 ADVANCED MATLAB

Introduction to MATLAB Practical 1

What is MATLAB and howtostart it up?

MATLAB Functions and Graphics

MATLAB BASICS. < Any system: Enter quit at Matlab prompt < PC/Windows: Close command window < To interrupt execution: Enter Ctrl-c.

What is Matlab? The command line Variables Operators Functions

Matlab Tutorial: Basics

INC151 Electrical Engineering Software Practice. MATLAB Graphics. Dr.Wanchak Lenwari :Control System and Instrumentation Engineering, KMUTT 1

Introduction in MATLAB (TSRT04)

Purpose of the lecture MATLAB MATLAB

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

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

Math 375 Natalia Vladimirova (many ideas, examples, and excersises are borrowed from Profs. Monika Nitsche, Richard Allen, and Stephen Lau)

Chapter 2. MATLAB Fundamentals

Introduzione a MatLab. Prof. Sebastiano Battiato

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

Transcription:

What is Matlab? A software environment for interactive numerical computations Examples: Matrix computations and linear algebra Solving nonlinear equations Numerical solution of differential equations Mathematical optimization Statistics and data analysis Signal processing Modelling of dynamical systems Solving partial differential equations Simulation of engineering systems

Matlab Background Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra routines (Lapak/Linpak) Commercialized 1984 by The Mathworks Since then heavily extended (defacto-standard) Alternatives Complements Octave (free) Maple (symbolic) Julia (free) Mathematica (symbolic) R (sort of) and (free)

or Start it up!

Display Windows

Help! help help command Eg., help plot Help on toolbar demo Read a matlab primer: http://math.ucsd.edu/~driver/21d-s99/matlab-primer.html https://www.mathworks.com/help/pdf_doc/matlab/getstart.pdf Try the tutorial in openwetware

Matlab Workspace Variables are stored here in the form of arrays (or matrices) which can be of different types: integers (int), real numbers (double), or alphabetical (string). All numerical operations need to be performed on double precision, takes 8 bytes per value. Who, whos current variables in workspace Save, load save or load variables to *.mat file Clear all clear all variables

First steps Assignments (not equations!!!!) >>x=4; >>y=2; >>z=2*x+3*y; >>z z = 14 You must make sure there s data in a variable before you use it in a computation!

Interactive Calculations Matlab is interactive, no need to declare variables >> 2+3*4/2 >> a=5e-3; b=1; a+b Most elementary functions and constants are already defined >> cos(pi) >> abs(1+i) >> sin(pi) >> exp(1) >> log(exp(1)) There are some built in numbers like: pi sin(pi) gives answer 1.2246e-016!? Try this (speakers on, not max volume tho) >> load handel >> sound(y,fs)

Vectors and Matrices Vectors (arrays) are defined as >> v = [1, 2, 4, 5] >> w = [1; 2; 4; 5] Matrices (2D arrays) defined similarly >> A = [1,2,3;4,-5,6;5,-6,7]

Matrix Operators All common operators are overloaded >> v + 2 Common operators are available >> B = A >> A*B >> A+B Note: Matlab is case-sensitive A and a are two different variables

Indexing Matrices Indexing using parentheses >> A(2,3) Index submatrices using vectors of row and column indices >> A([2 3],[1 2]) Ordering of indices is important! >> B=A([3 2],[2 1]) >> B=[A(3,2),A(3,1);A(2,2);A(2,1)]

Indexing Matrices Index complete row or column using the colon operator >> A(1,:) Can also add limit index range >> A(1:2,:) >> A([1 2],:) General notation for colon operator >> v=1:5 >> w=1:2:5

Matrix Functions Many elementary matrices predefined >> help elmat; >> I=eye(3) Elementary functions are often overloaded >> help elmat >> sin(a) Specialized matrix functions and operators >> As=sqrtm(A) >> As^2 >> A.*A Note: in general,.<operator> is elementwise operation

Graphics Visualization of vector data is available >> x=-pi:0.1:pi; y=sin(x); >> plot(x,y) >> plot(x,y, s- ) >> xlabel( x ); ylabel( y=sin(x) ); >> plot(x,y LineWidth, 4);

What kind of graphics is possible in Matlab? Polar plot: t=0:.01:2*pi; polar(t,abs(sin(2*t).*cos(2*t))); Line plot: x=0:0.05:5; y=sin(x.^2); plot(x,y); Stem plot: x = 0:0.1:4; y = sin(x.^2).*exp(-x); stem(x,y)

What kind of graphics is possible in Matlab? Mesh plot: z=peaks(25); mesh(z); Surface plot: z=peaks(25);surf(z);colormap(jet); Quiver plot? Contour plot: z=peaks(25);contour(z,16);

Plot Continue Adding plots to an existing graph: hold on Turn the above off hold off Multiple plots in one figure: subplot Create new plot windows figure

More Plotting Old plot got stomped To open a new graph, type figure Multiple data sets: Type hold on to add new plot to current graph Type hold off to resume stomping Make your graph beautiful: title( apples over oranges ) xtitle( apples ) ytitle( oranges )

Plotting (con t ) Example: (polynomial function) plot the polynomial using linear/linear scale, log/linear scale, linear/log scale, & log/log scale: y = 2x 2 + 7x + 9 % Generate the polynomial: x = 0:10:100; y = 2*x.^2 + 7*x + 9; % plotting the polynomial: figure (1); subplot (2,2,1), plot (x,y); title ('Polynomial, linear/linear scale'); ylabel ('y'), grid; subplot (2,2,2), semilogx (x,y); title ('Polynomial, log/linear scale'); ylabel ('y'), grid; subplot (2,2,3), semilogy (x,y); title ('Polynomial, linear/log scale'); xlabel('x'), ylabel ('y'), grid; subplot (2,2,4), loglog (x,y); title ('Polynomial, log/log scale'); xlabel('x'), ylabel ('y'), grid;

Plotting (con t )

Plotting (con t ) Adding new curves to the existing graph: Use the hold command to add lines/points to an existing plot. hold on retain existing axes, add new curves to current axes. Axes are rescaled when necessary. hold off release the current figure window for new plots Grids and Labels: Command grid on grid off grid title ( text ) xlabel ( text ) ylabel ( text ) text (x,y, text ) Description Adds dashed grids lines at the tick marks removes grid lines (default) toggles grid status (off to on, or on to off) labels top of plot with text in quotes labels horizontal (x) axis with text is quotes labels vertical (y) axis with text is quotes Adds text in quotes to location (x,y) on the current axes, where (x,y) is in units from the current plot.

Additional commands for plotting color of the point or curve Marker of the data points Plot line styles Symbol y m c r g b w Color yellow magenta cyan red green blue white Symbol Marker. o x + + * s Symbol Line Style solid line : dotted line. dash-dot line dashed line k black d v ^ h hexagram

3D - Plotting example x=[0:10]; y=[0:10]; z=x *y; mesh(x,y,z); title( 3-D Graph );

Graphics Bitmap images can also be visualized >> load mandrill >> image(x); colormap(map) >> axis image off

Programming with MATLAB: Files that contain code in the MATLAB language are called M-files. You create M- files using a text editor, then use them as you would any other MATLAB functions or command. There are two types of M-files: Scripts and Functions.

Programming in Matlab Script Files List of commands to be executed sequentially. Useful when same sequence is executed many times. They should be saved with extension script.m and should be placed on work path to be called. >>script runs the sequence Functions Similar to script, but takes arguments A funcname.m file starts with: function [output]=funcname(input) Any function can be listed with: >>type funcname See Matlab editor (File>New>m-file)

Scripts Scripts: a bunch of code grouped together; doesn t accept argument or return output. Example: create a file called magicrank.m that calculates the rank of magic squares: r = zeros(1,20); for n = 1:20 r(n) = rank(magic(n)); end bar(r) Add the file into search path and type the statement: magicrank

M-Files So far, we have executed the commands in the command window. But a more practical way is to create a M-file. The M-file is a text file that consists a group of MATLAB commands. MATLAB can open and execute the commands exactly as if they were entered at the MATLAB command window. To run the M-files, just type the file name in the command window. (make sure the current working directory is set correctly) All MATLAB commands are M-files.

M-files Functions M-files are macros of MATLAB commands that are stored as ordinary text files with the extension "m", that is filename.m example of an M-file that defines a function, create a file in your working directory named yplusx.m that contains the following commands: Write this file: function z = yplusx(y,x) z = y + x; -save the above file(2 lines) as yplusx.m x = 2; y = 3; z = yplusx(y,x)

Functions: Functions are M-files that can accept input arguments and return output arguments. The name of the M-file and of the function should be the same. For example, the M-file ode45.m is available in the directory: ~toolbox/matlab/funfun, you can see the file with type ode45

Flow Control: MATLAB has following flow controls: If statement Switch statement For loops While loops Continue statement Break statement

if elseif else end If A > B greater elseif A < B less elseif A = = B equal else error( Unexpected situation ) end

for end for i = 1:m for j = 1:n H(i,j) = 1/(i+j) end end

Suppressing Output: If you simply type a statement and press Enter, MATLAB automatically displays the results on screen. If you end the line with a semicolon ;, MATLAB performs the computation but does not display any result. Example: C = randn(5,1) v.s. C = randn(5,1);

Useful Commands Single quote is transpose % same as // comment in C, Java No /* block comments */ (annoying) ; suppresses printing More: max(x) mean(x) abs(x) cross(x,y) min(x) median(x) dot(x,y) flops (flops in this session)

Inf NaN eps Useful Constants infinity Not a number (div by zero) machine epsilon pi 3.14159. And a variable ans most recent unassigned answer

DE lesson Get the files from today on openwetware Run the script files Change the parameter values and rerun