What is Matlab? A software environment for interactive numerical computations Examples: –Matrix computations and linear algebra –Solving nonlinear equations.

Slides:



Advertisements
Similar presentations
MATLAB – A Computational Methods By Rohit Khokher Department of Computer Science, Sharda University, Greater Noida, India MATLAB – A Computational Methods.
Advertisements

StatLab Workshop Yale University Maximiliano Appendino, Economics October 18 th, 2013.
Introduction to Matlab
1 EMT 101 – Engineering Programming Dr. Farzad Ismail School of Aerospace Engineering Universiti Sains Malaysia Nibong Tebal Pulau Pinang Week 10.
Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
Introduction to MATLAB for Biomedical Engineering BME 1008 Introduction to Biomedical Engineering FIU, Spring 2015 Lesson 2: Element-wise vs. matrix operations.
MATLAB – What is it? Computing environment / programming language Tool for manipulating matrices Many applications, you just need to get some numbers in.
ECEN/MAE 3723 – Systems I MATLAB Lecture 1. Lecture Overview  Introduction and History  Matlab architecture  Operation basics  Visualization  Programming.
Introduction to Matlab By: Dr. Maher O. EL-Ghossain.
Introduction to Matlab Tutorial for CS4MN3/SE3X03 Wen Yu McMaster University.
Intro to Matlab 1.Vectors, matrices, and arithmetic 2.Plotting 3.Flow Constructs 4.Other Useful Things Can be found at:
Introduction to MATLAB MECH 300H Spring Starting of MATLAB.
Introduction to Matlab Jianguo Wang CSSCR September 2009.
Matlab intro The Environment
What is MATLAB ? MATrix LABratory –Originally, it was a front-end to FORTRAN matrix routines developed in the U. of New Mexico and Stanford –Today.
1 Introduction to MATLAB MATLAB is all of the following: 1.Computational environment 2.Plotting software 3.Programming language Typical applications: 1.Calculations.
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
Chapter 5 Review: Plotting Introduction to MATLAB 7 Engineering 161.
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
Martin Ellison University of Warwick and CEPR Bank of England, December 2005 Introduction to MATLAB.
Nonparametric Econometrics1 Intro to Matlab for Data Analysis and Statistical Modeling.
Mikael Johansson and Frank Lingelbach Department of Signals, Sensors and Systems Based on lectures by F. Gustafsson,
Introduction to MATLAB Session 1 Prepared By: Dina El Kholy Ahmed Dalal Statistics Course – Biomedical Department -year 3.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
Introduction to Matlab 1. Outline: What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators Plotting Flow Control Using of M-File Writing.
ELG 3120 Signal and System Analysis 1 Introduction to MATLAB TAs Wei Zhang Ozgur Ekici (Section A)(Section B) ELG 3120 Lab Tutorial 1.
How to Use MATLAB A Brief Introduction. 2 What can MATLAB do? Matrix Operations Symbolic Computations Simulations Programming 2D/3D Visualization.
1 Lab of COMP 406 Teaching Assistant: Pei-Yuan Zhou Contact: Lab 1: 12 Sep., 2014 Introduction of Matlab (I)
MEGN 536 – Computational Biomechanics MATLAB: Getting Started Prof. Anthony J. Petrella Computational Biomechanics Group.
ECE 1304 Introduction to Electrical and Computer Engineering Section 1.1 Introduction to MATLAB.
MATLAB Tutorial EE 327 Signals and Systems 1. What is MATLAB? MATLAB – Matrix Laboratory The premier number-crunching software Extremely useful for signal.
Eng Ship Structures 1 Introduction to Matlab.
INTRODUCTION TO MATLAB LAB# 01
Peng Liu Haas School of Business University of California, Berkeley
Matlab 14.html Cost: $100 Available in labs on Windows and Unix machines.
Introduction to Matlab. Outline:  What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display.
Chapter 1 – Matlab Overview EGR1302. Desktop Command window Current Directory window Command History window Tabs to toggle between Current Directory &
Master in Optical Fiber Communications and Photonic Technologies Foundations of Digital Transmission - Fall quarter Introduction to Matlab.
1 DKT 211 Basic Communication Engineering LAB # 1A : (Lecture 1) Introduction to Matlab  Basic Features  Scientific features  Array Operations  Script.
Introduction to Matlab. What is Matlab? A software environment for interactive numerical computations Examples:  Matrix computations and linear algebra.
INTRODUCTION TO MATLAB MATLAB is a software package for computation in engineering, science, and applied mathemat-ics. It offers a powerful programming.
Matlab Screen  Command Window  type commands  Current Directory  View folders and m-files  Workspace  View program variables  Double click on a.
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
Introduction to Matlab
Mikael Johansson and Frank Lingelbach Department of Signals, Sensors and Systems Based on lectures by F. Gustafsson,
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
ECE 351 M ATLAB I NTRODUCTION ( BY T EACHING A SSISTANTS )
NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS ( NET 222: COMMUNICATIONS AND NETWORKS FUNDAMENTALS (PRACTICAL PART) Tutorial 2 : Matlab - Getting Started.
CS100A, Fall 1998, Lecture 201 CS100A, Fall 1998 Lecture 20, Tuesday Nov 10 More Matlab Concepts: plotting (cont.) 2-D arrays Control structures: while,
An Introduction to Programming in Matlab Emily Blumenthal
MATLAB (Matrix Algebra laboratory), distributed by The MathWorks, is a technical computing environment for high performance numeric computation and.
Outline What is MATLAB MATLAB desktop Variables, Vectors and Matrices Matrix operations Array operations Built-in functions: Scalar, Vector, Matrix Data.
How to use MATLAB (using M-files) Double click this icon To start Matlab 6.5.
ECE 1304 Introduction to Electrical and Computer Engineering
Matlab Training Session 4: Control, Flow and Functions
Introduction to Matlab ( Google Search )
Outline Matlab tutorial How to start and exit Matlab Matlab basics.
MATLAB DENC 2533 ECADD LAB 9.
Matlab Workshop 9/22/2018.
StatLab Matlab Workshop
Part I – Matlab Basics.
MATLAB How to use (using M-files) Double click this icon
MATLAB Tutorial Dr. David W. Graham.
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
MATLAB How to use (using M-files) Double click this icon
Lecture 2 Introduction to MATLAB
Communication and Coding Theory Lab(CS491)
Vectors, matrices, and arithmetic
How to Use MATLAB A Brief Introduction.
Presentation transcript:

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) AlternativesComplements Octave (free) Maple(symbolic) Julia (free)Mathematica(symbolic) R (sort of) and (free)

Start it up! or

Display Windows

Help! help help command Eg., help plot Help on toolbar demo Read a matlab primer: – – 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 e-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, ”. ” 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); Contour plot: z=peaks(25);contour(z,16); Quiver plot?

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…)

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: CommandDescription grid onAdds dashed grids lines at the tick marks grid offremoves grid lines (default) gridtoggles grid status (off to on, or on to off) title (‘text’)labels top of plot with text in quotes xlabel (‘text’)labels horizontal (x) axis with text is quotes ylabel (‘text’)labels vertical (y) axis with text is quotes text (x,y,’text’)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 SymbolColor yyellow mmagenta ccyan rred ggreen bblue wwhite kblack SymbolMarker.  o  x  ++ *  s□ d◊ v  ^  hhexagram color of the point or curve Marker of the data pointsPlot line styles SymbolLine Style –solid line :dotted line –.dash-dot line – dashed line

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 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. So far, we have executed the commands in the command window. But a more practical way is to create a M-file.

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

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)min(x) mean(x)median(x) abs(x)dot(x,y) cross(x,y)flops (flops in this session)

Useful Constants Inf infinity NaN Not a number (div by zero) epsmachine epsilon pi …. And a variable ansmost recent unassigned answer

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