AMS597 Spring 2011 Hao Han April 05, 2011 1. Introduction to MATLAB The name MATLAB stands for MATrix LABoratory. Typical uses include:  Math and computation.

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

259 Lecture 17 Working with Data in MATLAB. Overview  In this lecture, we’ll look at some commands that are useful for working with data!  fzero  sum,
Introduction to MATLAB The language of Technical Computing.
Introduction to M ATLAB Programming Ian Brooks Institute for Climate & Atmospheric Science School of Earth & Environment
Introduction to Matlab
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 - Basics Centro de Informática Universidade Federal de Pernambuco Aprendizagem de Máquina – IN1102 Arley Ristar –
Introduction to MATLAB Simon O’Keefe Non-Standard Computation Group
Introduction to MATLAB
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 18P. 1Winter Quarter Introduction to MATLAB.
Exam #3 Review: Comprehensive Exam Class 14.2 Palm Matlab Book Ch. 1-5.
Getting started with Matlab Numerical Methods Appendix B help/techdoc/learn_matlab/learn_matlab.html.
Dr. Jie Zou PHY Welcome to PHY 3320 Computational Methods in Physics and Engineering.
Introduction to MATLAB MECH 300H Spring Starting of MATLAB.
Introduction to MATLAB
Matlab intro The Environment
MATLAB Fundamentals.
Chapter 10 Review: Matrix Algebra
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
1 Statistical Computing in MATLAB AMS 597 Ling Leng.
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.
1 M ATLAB Short Course. History of Calculator 2 3 Introduction to Matlab Matlab is short for Matrix Laboratory Matlab is also a programming language.
You can make this in matlab!. Matlab Introduction and Matrices.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
MATLAB Tutorials Session I Introduction to MATLAB Rajeev Madazhy Dept of Mechanical Engineering LSU.
Introduction to Matlab 1. Outline: What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators Plotting Flow Control Using of M-File Writing.
Introduction to MATLAB
Introduction to MATLAB CBE 502 Mathematical Methods of Engineering Analysis.
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.
A Brief Introduction to Matlab Laila Guessous Dept. of Mechanical Engineering Oakland University.
INTRODUCTION TO MATLAB LAB# 01
Matlab Programming for Engineers Dr. Bashir NOURI Introduction to Matlab Matlab Basics Branching Statements Loops User Defined Functions Additional Data.
Basics of MATLAB By DR. Wafaa Shabana
Matlab 14.html Cost: $100 Available in labs on Windows and Unix machines.
ES 240: Scientific and Engineering Computation. Chapter 2 Chapter 2: MATLAB Fundamentals Uchechukwu Ofoegbu Temple University.
Introduction to MATLAB. CSPP58001 MATLAB MATLAB is is a matrix-based language well suited for carrying out numerical analysis. It has many, many high-
ME6104: CAD. Module 4. ME6104: CAD. Module 4. Systems Realization Laboratory Module 4 Matlab ME 6104 – Fundamentals of Computer-Aided Design.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 18P. 1Winter Quarter Introduction to MATLAB Lecture 18.
Introduction to Matlab. What is Matlab? A software environment for interactive numerical computations Examples:  Matrix computations and linear algebra.
Introduction to Matlab By E. Noura Semary. Contents MATLAB Environment  Command window, Workspace, Path window, Editor window,and Figure window) Basic.
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
A Quick Octave Tutorial 阮 翀
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
Introduction to Matlab Electromagnetic Theory LAB by Engr. Mian Shahzad Iqbal.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
CSE 455 : Computer Vision MATLAB 101 Getting Started with MATLAB.
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
Introduction to Matlab Engr. Mian Shahzad Iqbal LAB NO.2
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.
ECE 1304 Introduction to Electrical and Computer Engineering
Introduction to Mat lab
Statistical Computing in MATLAB
Outline Matlab tutorial How to start and exit Matlab Matlab basics.
INTRODUCTION TO BASIC MATLAB
MATLAB DENC 2533 ECADD LAB 9.
Introduction to Matlab
Matlab Workshop 9/22/2018.
MATLAB PRIMER by Michael Medvinsky(2014)
StatLab Matlab Workshop
Use of Mathematics using Technology (Maltlab)
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
INTRODUCTION TO MATLAB
How to Use MATLAB A Brief Introduction.
CS 111 Introduction to Computing in Engineering and Science
Presentation transcript:

AMS597 Spring 2011 Hao Han April 05,

Introduction to MATLAB The name MATLAB stands for MATrix LABoratory. Typical uses include:  Math and computation – Algorithm development – Data acquisition – Modeling, simulation, and prototyping  Data analysis, exploration, and visualization – Scientific and engineering graphics – Application development, including graphical user interface (GUI) building We will focus on the statistical computing in MATLAB. 2

3 Desktop Tools & Development Environment Workspace Browser – View and make changes to the contents of the workspace. Command Windows – Run MATLAB statements (commands).  Hotkey: Ctrl+c -> break while the status is busy M-file Editor – Creating, Editing, Debugging and Running Files.

MATLAB Variables Variable names are case sensitive. Variable names must start with a letter and can be followed by digits and underscores. MATLAB does not require any type of declarations or dimension statements. When it encounters a new variable name, it automatically creates the variable and allocates the appropriate amount of storage. For example: New_student = 25; To view the matrix assigned to any variable, simply enter the variable name. Special Variables: pivalue of π epssmallest incremental number inf infinity NaNnot a number realminthe smallest usable positive real number realmaxthe largest usable positive real number 4

MATLAB Matrices MATLAB treats all variables as rectangular matrices. Separate the elements of a row with blanks or commas. Use a semicolon ‘;’ to indicate the end of each row. Surround the entire list of elements with square brackets ‘[ ]’. Claim a matrix: a = [1 2 3; 4 5 6; 7 8 9] a = Subscripts: the element in row i and column j of A is denoted by A(i,j). a(3,2)=8 or a(6)=8 Claim a scalar: x = 2; Claim a row vector: r = [1 2 3] r = [1,2,3] Claim a column vector: c = [1;2;3] c = [1 2 3]’ 5

Matrix Manipulations The Colon Operator: 1:5 is a row vector containing integers from 1 to 5. To obtain non-unit spacing, specify an increment. For example, 100:-7:50 Extracting a sub-matrix: Sub_matrix = matrix(r1:r2,c1:c2); sub_a = a(2:3,1:2) sub_a = Replication: b = [1 2; 3 4]; b_rep = repmat(b,1,2) b_rep = Concatenation: c = ones(2,2); c_cat = [c 2*c; 3*c 4*c] c_cat = c_cat = cat(DIM,A,B); Deleting rows or columns: c_cat(:,2)=[]; 6

Structures and Cell Arrays Structure Cell Array Way of organizing related data Create a structure, s, with fields, x, y, and name s.y = 1; s.x = [1 1]; s.name = 'foo'; % or equivalenty s2 = struct('y',1,'x',[1 1],'name','foo'); Test for equality: % works for any s1, s2 isequal(s1,s2); Cell arrays can have entries of arbitrary datatype % create 3 by 2 cell array a = cell(3,2); a{1,1} = 1; a{3,1} = 'hello'; a{2,2} = randn(100,100); Using cell arrays with other datatypes can be tricky % create 2 by 1 cell array a = {[1 2], 3}; y = a{1}; % y is 1 by 2 numeric array ycell =a(1); % is 1 by 1 cell array x = y+1; % allowed xcell = ycell+1; % not allowed onetwothree = [a{1:2}]; % = [1 2 3] 7

MATLAB Operators Relational operators: Less than< Less than or Equal<= Great than or Equal>= Equal to== Not equal to ~= Logical operators: not ~ % highest precedence and & % equal precedence with or or| % equal precedence with and Matrix computations: + - * / ^ A’; % transpose A \ b; % returns x s.t. A*x=b A / b; % returns x s.t. x*A=b Element wise operators: + Addition - Subtraction.*Element-by-element multiplication./Element-by-element division.\Element-by-element left division.^Element-by-element power.' Unconjugated array transpose 8

MATLAB Functions MATLAB provides a large number of standard elementary mathematical functions, including abs, sqrt, exp, and sin. For a list of the elementary mathematical functions, type: help elfun For a list of more advanced mathematical and matrix functions: help specfun help elmat Seek help for MATLAB function references, type: help somefun or more detailed doc somefun 9

Flow Control (‘if’ statement) The general form of the ‘ if ’ statement is if expression … elseif expression … else … end Example 1: if i == j a(i,j) = 2; elseif i >= j a(i,j) = 1; else a(i,j) = 0; end Example 2: if (common>60)&&(area>60) pass = 1; end 10

Flow Control (‘switch’ statement) switch Switch among several cases based on expression The general form of the switch statement is: switch switch_expr case case_expr1 … case case_expr2 … otherwise … end Example : x = 2, y = 3; switch x case x==y disp('x and y are equal'); case x>y disp('x is greater than y'); otherwise disp('x is less than y'); end % x is less than y 11

Flow Control (‘for’ loop) for Repeat statements a specific number of times The general form of a for statement is for variable=expression … end Example 1: for x = 0:0.05:1 fprintf('%3.2f\n',x); end Example 2: a = zeros(3,4); for i = 1:3 for j = 1:4 a(i,j) = 1/(i+j); end 12

Flow Control (‘while’ loop) while Repeat statements an indefinite number of times The general form of a while statement is while expression … end Example 1: n = 1; y = zeros(1,10); while n <= 10 y(n) = 2*n/(n+1); n = n+1; end Example 2: x = 1; while x %execute statements end 13

Flow Control (‘break’ statement) break terminates the execution of for and while loops In nested loops, break terminates from the innermost loop only Example: y = 3; for x = 1:10 fprintf( ' %d\n ',x); if (x>y) break; end % Question: what is the output? 14

Graphics: 2-D plot Basic commands: Example 1 [plot(vector)]: plot(x, 's') plot(x,y, 's') plot(x1, y1, 's1', x2,y2, 's2', …) title('…') xlabel('…') ylabel('…') legend('…', '…') x=0:pi/10:2*pi; x=[sin(x)' cos(x)']; figure; plot(x) 15

Graphics: 2-D plot (cont’d) Example 2: Example 3 [plot(vector,matrix)]: t=(0:pi/50:2*pi)'; k=0.4:0.1:1; Y=cos(t)*k; plot(t,Y) x = 0:0.01:2*pi; y = sin(x); z = cos(x); hold on; plot(x,y, 'b'); plot(x,z, 'g'); hold off; 16

Graphics: 2-D plot (cont’d) plot(x1, y1,’s1’, x2,y2,’s2’, …) t=(0:pi/100:pi)'; y1=sin(t)*[1,-1]; y2=sin(t).*sin(9*t); t3=pi*(0:9)/9; y3=sin(t3).*sin(9*t3); plot(t,y1,'r:',t,y2,'b',t3,y3,'bo') axis([0,pi,-1,1]) Linetype - : Color b g r c m y k w Markertype. + * ^ v d h o p s x plot(t,y1,'.r',t,y2, 'b+',t3,y3,'ob:') 17

Subplots >> subplot(2,2,1) >> … >> subplot(2,2,2) >> … >> subplot(2,2,3) >> … >> subplot(2,2,4) >> … 18

Graphics: 3-D plot plot3(x,y,z) t=(0:0.02:2)*pi;x=sin(t);y=cos(t);z=cos(2*t); plot3(x,y,z,'b-',x,y,z,'bd'); view([-82,58]); box on; legend('Chain','Gemstone') 19

20

Basic Data Analysis Import/Export data:  Use the system import wizard File -> import data -> find and open files -> finish  Use commands as follows: 1. help load & help save 2. help xlsread & help xlswrite % Reading into a text file fid = fopen(‘filename.txt’,‘r’); X = fscanf(fid,‘%5d’); % or fread fclose(fid); % Writing onto a text file fid = fopen(‘filename.txt’,‘w’); count = fwrite(fid,x); % or fprintf fclose(fid); Scatter plot Statistics Toolbox: help stats Basic Data Analysis Function (help datafun) FunctionDescription cumprod Cumulative product of elements. cumsum Cumulative sum of elements. cumtrapz Cumulative trapezoidal numerical integration. diff Difference function and approximate derivative. max Largest component. mean Average or mean value. median Median value. min Smallest component. prod Product of elements. sort Sort array elements in ascending or descending order. sortrows Sort rows in ascending order. std Standard deviation. sum Sum of elements. trapz Trapezoidal numerical integration. covCovariance matrix corrcoefCorrelation coefficients 21

22 Data Preprocessing Missing values: You should remove NaNs from the data before performing statistical computations. Removing outliers: You can remove outliers or misplaced data points from a data set in much the same manner as NaNs. 1. Calculate the mean and standard deviation from the data set. 2. Get the column of points that lies outside the 3*std. (3σ-rule) 3. Remove these points CodeDescription i = find(~isnan(x)); x = x(i) Find indices of elements in vector that are not NaNs, then keep only the non-NaN elements. x = x(find(~isnan(x)))Remove NaNs from vector. x = x(~isnan(x));Remove NaNs from vector (faster). x(isnan(x)) = [];Remove NaNs from vector. X(any(isnan(X)'),:) = [];Remove any rows of matrix X containing NaNs.

23 Regression and Curve Fitting The easiest way to find estimated regression coefficients efficiently is by using the MATLAB backslash operator. Note that we should avoid matrix inversion (from slow to fast…): % Fit X*b=Y xx = x’*x;xy=x’*y; tic; bhat1 = (xx)ˆ(−1)*xy; toc; tic; bhat2 = inv(xx)*xy; toc; tic; bhat3 = xx \ xy; toc; Other ways use build-in functions: regress() or glmfit() Multiple linear regression model: y = b 0 + b 1 x 1 + b 2 x 2 + … Example: Suppose you measure a quantity y at several values of time t. t=[ ]'; y=[ ]'; plot(t,y,'o') grid on

Regression Example (cont’d) Polynomial regression: There are six equations in three unknowns, represented by the 6-by-3 matrix X = [ones(size(t)) t t.^2] The solution is found with the backslash operator. a = X\y a = Now evaluate the model at regularly spaced points and overlay the original data in a plot. T=(0:0.1:2.5)'; Y=[ones(size(T)) T T.^2]*a; plot(T,Y,'-',t,y,'o') grid on 24

Regression Example (cont’d) Linear-in-the-parameters regression, e.g. exponential function: X = [ones(size(t)) exp(-t) t.*exp(-t)]; a = X\y a = T=(0:0.1:2.5)'; Y=[ones(size(T)) exp(-T) T.*exp(-T)]*a; plot(T,Y,'-',t,y,'o') grid on 25

26